1

code

lst = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for i in lst:
    i.append(0)

makes lst look like this [[1, 2, 3, 0], [4, 5, 6, 0], [7, 8, 9, 0]]

The result is unexpected for me, since usually when we loop through a list, in i we seem to get a *copy *of the next value. I mean, code

for i in lst:
    i = 3

doesn't change anything in the lst, so in every iteration i is just a temporary copy, right?

Alex
  • 11
  • 1
  • 2
    lists are mutable, integers are not. Also `i.append(0)` applies to the object, `i = 3` just redefines the name – mozway Jul 05 '23 at 13:57
  • Of course your last code doesn't change anything in `lst` because you're not modifying it at all. – Avantgarde Jul 05 '23 at 13:59
  • 2
    During the 1st passage in the loop, `i` points to the sublist `[1, 2, 3]` ; `i.append(0)` modifies this sublist in place, hence the result; on the other hand, `i = 3` makes i 'forget' the sublist and point to the integer 3 instead. – Swifty Jul 05 '23 at 14:00
  • 1
    Lists are mutable. list.append is a method that mutates the object (changes the inner state of the object). The variable still points to the same place in memory because you don't do anything with variable `i`, you do stuff with inner state of the object. But any time you do i= anywhere, the memory that the variable points to changes (unless of course you do an assignment with itself that does nothing). It's not like in C or other languages that variable itself is a place of memory - in Python each variable is basically a pointer to something else – h4z3 Jul 05 '23 at 14:07
  • This might be something you want to read: [Facts and myths about Python names and values](https://nedbatchelder.com/text/names.html) – Matthias Jul 05 '23 at 14:46

0 Answers0