Modifying values in a list

Brian van den Broek broek at cc.umanitoba.ca
Thu Dec 29 17:56:35 CET 2005


tron.thomas at verizon.net said unto the world upon 29/12/05 10:43 AM:
> 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?

value is bound in the for loop, but none of that affects the list to 
which numbers is bound.

One way:

IDLE 1.1.2
 >>> numbers = [1, 2, 3]
 >>> numbers = [x * 2 for x in numbers]
 >>> print numbers
[2, 4, 6]
 >>>

HTH,

Brian vdB



More information about the Python-list mailing list