-1

Here's a snippet that I am finding puzzling. Why is that y[0][0] = 2 initializing all the columns in all rows?

Python 3.8.10 (default, Jun  2 2021, 10:49:15) 
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> x = []
>>> x.append([0])
>>> x.append([0])
>>> x.append([0])
>>> x.append([0])
>>> x
[[0], [0], [0], [0]]
>>> y = [ [0] * 1 ] * 4
>>> y
[[0], [0], [0], [0]]
>>> x == y
True
>>> x[0][0] = 2
>>> y[0][0] = 2
>>> x
[[2], [0], [0], [0]]
>>> y
[[2], [2], [2], [2]]
>>> 
sradhakrishna
  • 99
  • 1
  • 5

2 Answers2

1

In the line y = [ [0] * 1 ] * 4 what the Python interpreter is actually doing is creating a list that has 4 pointers to the same object. You are actually creating one list [0] and 4 references to the same list. When you alter one of them, you alter all of them.

1

It has to do with how you're initializing y:

y = [ [0] * 1 ] * 4

This basically says 'create a list with a single element, 0'. Then it says 'put that list four times into a new list'. Thus, if you change the original list, you change all the subsequent copies (references, really) you made, since they each point to the same piece of memory.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102