lists and for loops

Tim Chase python.list at tim.thechases.com
Thu Aug 18 14:45:10 CEST 2011


On 08/18/2011 07:22 AM, Mark Niemczyk wrote:
> Or, using list comprehension.
>
>>>> numbers = [1, 2, 3, 4, 5]
>>>> numbers = [n + 5 for n in numbers]
>>>> numbers
> [6, 7, 8, 9, 10]

Or, if you want it in-place:

   numbers[:] = [n+5 for n in numbers]

which makes a difference if you have another reference to numbers:

 >>> numbers = [1,2,3,4,5]
 >>> digits = numbers
 >>> numbers = [n+5 for n in numbers]
 >>> numbers, digits
([6, 7, 8, 9, 10], [1, 2, 3, 4, 5])
 >>> numbers = [1,2,3,4,5]
 >>> digits = numbers
 >>> numbers[:] = [n+5 for n in numbers]
 >>> numbers, digits
([6, 7, 8, 9, 10], [6, 7, 8, 9, 10])

-tkc






More information about the Python-list mailing list