[Tutor] Re: References in loops
Andrei
project5 at redrival.net
Sat Feb 12 01:38:18 CET 2005
Matt Dimmic wrote:
> In Python, one bug that often bites me is this:
>
> (example A)
> aList = [1,2,3]
> for i in aList:
> i += 1
> print aList
> --> [1,2,3]
Numbers are immutable, so the element 1 can't change into a 2 inside the
list. If 1 was not immutable, e.g. a list you could modify it and then
it would be "updated" in the original list too.
> This goes against my intuition, which is that aList == [2,3,4], probably
> because so much in Python is passed by reference and not by value. Of
> course I can always use range() or enumerate():
I tend to use list comprehensions for this:
aList = [elem+1 for elem in aList]
but it's barely shorter than the explicit loop, so not necessarily an
improvement from that point of view. But at least it prevents the bug
from biting :).
Yours,
Andrei
More information about the Tutor
mailing list