I tried the following code on Python, and this is what I got:
It seems like for many changes I try to make to the iterables by changing elem, it doesn’t work.
lis = [1,2,3,4,5]
for elem in lis:
elem = 3
print lis
[1, 2, 3, 4, 5]
However if the iterables are objects with its own methods (like a list), they can be modified in a for loop.
lis = [[1],[2]]
for elem in lis:
elem.append(8)
print lis
[[1, 8], [2, 8]]
In the for loop what exactly is the ‘elem’ term? Thanks in advance!
The reason that this doesn’t work is because you’re misunderstanding what
elemis. It’s not the object itself, and it’s not even correct to call it a “variable”.It’s a name, kind of like a label, that points to the object. If you just directly assign over it, you’re just overwriting the name to point at something else. But, you still have the original reference to the list, so assigning a different value over
elemdoesn’t modifylisitself.Now, in this case, since all of the objects that
elempoints to are integers, you can’t even change them at all – because integers (and many other types, like strings or tuples) are immutable. That means, simply put, that once the object has been created it cannot be modified. It has nothing to do with whether they “have methods” or not (all Python objects have methods, integers included), but on whether or not they are immutable.Some objects, however, are mutable, meaning that they can be changed. Lists are examples of such objects. In your second example,
elemis a name that references the list objects contained withinlis, which themselves are mutable. That is why modifying them in-place (using.append(), or.remove(), etc) works fine.