When using a for loop in Python to iterate over items in a list, will changing item (below) change the corresponding item in items?
for item in items:
item += 1
Will each item in items be incremented or remain the same as before the loop?
No, variables in Python are not pointers.
They refer to objects on a heap instead, and assigning to a variable doesn’t change the referenced object, but the variable. Variables and objects are like labels tied to balloons; assignment reties the label to a different balloon instead.
See this previous answer of mine to explore that idea of balloons and labels a bit more.
That said, some object types implement specific in-place addition behaviour. If the object is mutable (the balloon itself can change), then an in-place add could be interpreted as a mutation instead of an assignment.
So, for integers,
item += 1is really the same asitem = item + 1because integers are immutable. You have to create a new integer object and tie theitemlabel to that new object.Lists on the other hand, are mutable and
lst += [other, items]is implemented as alst.__iadd__([other, items])and that changes thelstballoon itself. An assignment still takes place, but it is a reassigment of the same object, as the.__iadd__()method simply returnsselfinstead of a new object. We end up re-tying the label to the same balloon.The loop simply gives you a reference to the next item in the list on each iteration. It does not let you change the original list itself (that’s just another set of balloon labels); instead it gives you a new label to each of the items contained.