As everyone else pointed out, the correct way to do this is by indexing into the list:
myList = range(5)
for i in range(len(myList)):
myList[i] *= 2
print myList #[0,2,4,..]
A Little Bit About Pass By Assignment
Your loop, which uses the for num in list
notation does not modify the list. Because the loop variable num
takes a value of type int at each iteration of the loop, since ints are immutable (i.e its value cannot be changed) in python, num
gets a copy of the integer value.
This changes when the object in the list is mutable and is passed by reference. Consider the following:
class X:
def __init__(self):
self.val = 1
myList = [X() for i in range(5)]
print [element.val for element in myList] #1,1,1,1,1
for el in myList:
el.val = 2
print [element.val for element in myList] #2,2,2,2,2
Now, since myList contains a list of X objects which are mutable, the loop variable el
has a reference copied into it. The reference points to the same object in memory that the reference in original myList points to. So when you change the object using the loop variable, the objects referred to in the original myList are also changed.
This Pass By Reference talks about it in greater depth.