[Tutor] References in loops

Matt Dimmic reg at plaguerats.net
Fri Feb 11 22:52:20 CET 2005


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]

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():

(example B)
aList = [1,2,3]
for i in range(len(aList)):
    aList[i] += 1
print aList
--> [4,5,6]

But example A seems more elegant, if only it did what I wanted it to do.
:) So pardon my ignorance if the answer is obvious, but what is the
simplest way in Python to get a reference to an element in a list? Is it
really Example B?

Thanks,
Matt

(My apologies if this double-posts; I accidentally sent it previously
from a non-subscribed address. Moderator, please deny the other copy.)




More information about the Tutor mailing list