lists and for loops
jacktradespublic at gmail.com
Wed Aug 17 23:33:53 EDT 2011
> I want to add 5 to each element of a list by using a for loop.
> Why doesn't this work?
> numbers = [1, 2, 3, 4, 5]
> for n in numbers:
> n = n + 5
> print numbers
The n variable in the for loop refers to each value in the list, not the
reference to the slot that value is stored in.
To update the numbers list you would want something like this:
numbers = [1, 2, 3, 4, 5]
for n in range(len(numbers)):
numbers[n] += 5
Alternatively if you didn't need to update the numbers list you could make a
new list like this:
[n+5 for n in numbers]
Jack Trades <http://www.rentageekit.com>
Pointless Programming Blog <http://pointlessprogramming.wordpress.com>
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list