Here you are actually modifying the list object in the second example. In the first example, you do not change the number; you replace it. This can be a tricky nuance for new Python users.
Check this:
>>> x = 1 >>> id(x) 4351668456 >>> x = 2 >>> id(x) 4351668432
id returns the identifier of the object. As you can see above, the object x modifies both of these times.
>>> y = [1] >>> id(y) 4353094216 >>> y.append(2) >>> id(y) 4353094216
Here I am modifying the list, so the list is still the original y object.
So, all this means that when you do elem = 3 , it does not change it, it replaces it. And by now, he is no longer associated with this list.
This is one way to do what you are trying to do. This captures the index, and then modifies the list, not the number.
lis = [1,2,3,4,5] for idx, elem in enumerate(lis): lis[idx] = 3 print lis [1, 2, 3, 4, 5]
source share