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.)


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to