lists and for loops
alex23
wuwei23 at gmail.com
Thu Aug 18 05:23:17 CEST 2011
On Aug 18, 1:08 pm, Emily Anne Moravec <mora... at stolaf.edu> wrote:
> 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
As the for loop steps through numbers, it assigns each integer value
to the label n. What n holds is a number, _not_ a reference to the
number in the list. So when you reassign n to hold n+5, you're
pointing n at a new number, not modifying the original number being
referred to.
So what you need is a reference to the position of the number in the
list, so you can reassign the value that's held there. The common
pattern is to use enumerate, which lets you step through a list giving
you both an reference (index) & a value:
numbers = [1, 2, 3, 4, 5]
for i, n in enumerate(numbers):
numbers[i] = n + 5
Here you're reassigning each list element to hold its old value plus
5.
Hope this helps.
More information about the Python-list
mailing list