0

I have come across a strange behaviour in Python's value assignment. If I create a list such as List =[[0, 0], [0, 0]] and want to change a value indexed 1 in the list indexed as 1 I simply use: List[1][1] = 1. However, this is not a case of the code below. Eventhough the list seems same as the one mentioned above, it assigns more values then I expect. Is there anyone who can explain how this work?

size = 2
matrix = [[]]
for j in range(size):
    matrix[0].append(0)
for i in range(size-1):
    matrix.append(matrix[0])
matrix[1][1] = 1
print(str(matrix))

I would expect the output as [[0, 0], [0, 1]], but the actual output is [[0, 1], [0, 1]]. Why is the value at position matrix[0][1] assigned as 1??

Andyy
  • 1
  • 1
  • You only work with one list inside your outer list. `matrix[0]`, i.e. matrix contains the same list twice. You need to explicitly copy it when you add it – juanpa.arrivillaga Mar 29 '19 at 22:41

1 Answers1

0

When you do:

matrix.append(matrix[0])

You're appending to matrix the reference to the object matrix[0] (which is a list), it isn't creating a new list.

Elias Dorneles
  • 22,556
  • 11
  • 85
  • 107