lists and for loops
Peter Pearson
ppearson at nowhere.invalid
Thu Aug 18 12:43:20 EDT 2011
On Wed, 17 Aug 2011 20:08:23 -0700 (PDT), Emily Anne Moravec 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
Because integers are immutable. You cannot turn 1 into 6.
Contrast this behavior with lists, which *are* mutable:
>>> numbers = [[1],[2],[3],[4],[5]]
>>> for n in numbers:
... n[0]= n[0] + 5
...
>>> numbers
[[6], [7], [8], [9], [10]]
For practical purposes, I'm sure you'll find other responders'
excellent posts to be of more immediate use, but keeping
mutability in mind helps.
--
To email me, substitute nowhere->spamcop, invalid->net.
More information about the Python-list
mailing list