lists and for loops

Jack Trades jacktradespublic at gmail.com
Thu Aug 18 05:33:53 CEST 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
print numbers

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...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110817/fa51d49e/attachment.html>


More information about the Python-list mailing list