0
square = [[0 for i in range(3)] for j in range(3)]
square
>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
square[0][0] = 1
>> [[1, 0, 0], [0, 0, 0], [0, 0, 0]]

This is the expected behavior.

But then:

square = [[0] * 3] * 3
square
>> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
square[0][0] = 1
>> [[1, 0, 0], [1, 0, 0], [1, 0, 0]]

It seems like each list within the list is passed by reference to a list stored in memory.

I found this to be weird behaviour since I didn't explicitly create the sublist as an independent variable, and I wondered if anybody had thoughts to share on this...

0 Answers0