>
> 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>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to