Modifying values in a list
Carsten Haese
carsten at uniqsys.com
Thu Dec 29 11:56:41 EST 2005
On Thu, 2005-12-29 at 11:43, tron.thomas at verizon.net wrote:
> The following code:
>
> numbers = [1, 2, 3]
> for value in numbers:
> value *= 2
> print numbers
>
> results in the following output:
> [1, 2, 3]
>
> The intent of the code was to produce this output:
> [2, 4, 6]
>
> What is the reason for the output produced?
> What code should be used to obtain the desired output?
1) Read http://www.effbot.org/zone/python-objects.htm and reread it
until you understand why your code doesn't work.
2) Use a list comprehension:
numbers = [ value*2 for value in numbers ]
-Carsten
More information about the Python-list
mailing list