If I have a list of numbers, and I want to increment them using a for loop, why isn\'t this working:
>>> list=[1,2,3,4,5]
>>> for num in l
This is an artifact of how assignment works in python. When you do an assignment:
name = something
You are taking the object something
(which is the result of evaluating the right hand side) and binding it to the name name
in the local namespace. When you do your for
loop, you grab a reference to an element in the loop and then you construct a new object by adding 1 to the old object. You then assign that new object to the name num
in your current namespace (over and over again).
If the objects in our original list are mutable, you can mutate the objects in a for loop:
lst = [[],[],[]]
for sublst in lst:
sublst.append(0)
And you will see those changes in the original list -- Notice however that we didn't do any assignment here.
Of course, as suggested by lattyware, you can use a list-comprehension to construct a new list:
new_list = [x+1 for x in old_list]
and you can even make the assignment happen in place:
old_list[:] = [x+1 for x in old_list]