0

I have 2 examples below:

Example 1:

simplelist = [0] * 2
for i in range(2):
    simplelist[i] = i
print(simplelist)

result: [0, 1]

Example 2:

listinlist = [[0]] * 2
for i in range(2):
    listinlist[i][0] = i
print(listinlist)

result: [[1], [1]]

As you can see, in the 1st example, the two 0s appear not related to each other, and the code works as expected. However, when I replace the 0s with [0]s in example 2, the two [0]s appear related as if they are referenced to the same object. I think when I assign values to each of them, I assign values to the same object twice, so the second value 1 overwrites the first value 0. Please correct me if I am wrong and help me understand this issue. If you think it is not a referencing issue, please also share your opinion.

khelwood
  • 55,782
  • 14
  • 81
  • 108
c78250125
  • 13
  • 3
  • In the second example, `listinlist` contains two references to one single list. It doesn't hold two separate lists. Or in other words, `*` doesn't copy the object, it copies the reference to the object. – Carcigenicate Jan 11 '22 at 15:34
  • This isn't inconsistent at all. In *both* cases, `[x]*2` creates a *new list* with two references to the object inside, i.e. `x`. In one case, that object is an `int`, in the other it is a list. In the second case, you *mutate* that object. In the first case, you don't, you simply assign another value at that index. You'd see the same behavior in the second case if you did something *equivalent*, like `listinlist[i] = [i]` – juanpa.arrivillaga Jan 11 '22 at 15:50

0 Answers0