0

This is surely a very numb question... Let numbers=[0,1,2,3,4]. What's the difference between these two pieces of code? I would expect them to work the same way but the first one does not modify the list while the second does.

for item in numbers:
    item +=1

for i in range(len(numbers)):
    numbers[i] +=1
Giulio
  • 117
  • 2
  • Do you know what `+=` is shorthand for? – Scott Hunter Nov 15 '21 at 16:37
  • 2
    The first one doesn't change the list elements, it just updates the variable `item`. – Barmar Nov 15 '21 at 16:37
  • 1
    The first one is a kind of sugar for: ```for i in range(len(numbers)): item = numbers[i]; item += 1``` Then, it wont' update ```numbers``` at all. The second uses ```numbers``` directly => It's updated – Metapod Nov 15 '21 at 16:37
  • 2
    Try doing `print(numbers)` after each piece of code. – Barmar Nov 15 '21 at 16:38
  • 1
    `item` is a **reference** to an item in the numbers list, not an actual item in the list. – JacobIRR Nov 15 '21 at 16:41
  • Does this answer your question? [Python why loop behaviour doesn't change if I change the value inside loop](https://stackoverflow.com/questions/54799322/python-why-loop-behaviour-doesnt-change-if-i-change-the-value-inside-loop) – Yevhen Kuzmovych Nov 15 '21 at 16:44

1 Answers1

2

The item variable in the for-loop is independent from the list so modifying it has no effect on the list (it only modifies the item variable). But when you get the index (i) and use it to increase the ith item, then you are affecting with the original list's content.

Alain T.
  • 40,517
  • 4
  • 31
  • 51
  • 1
    Worth noting that this is true only for the immutable objects (like `int` in this case (probably)). Mutable objects could be changed with `item += 1`. It doesn't "modify" the `item` variable it rewrites the `item` reference with another integer reference. – Yevhen Kuzmovych Nov 15 '21 at 16:44