-1

Recently while I was practicing Python, I came up with the problem. I created two different empty lists one using list comprehension and next using the "multiplication" way.

Structurally both the lists are similar.

Afterwards, when I assign the value of array[0][0]=1 and try to print the list the result goes like this.

a=[[0 for i in range(3)] for j in range(3)]

b=[[0]*3]*3

print(a)
print("#####")
print(b)


a[0][0]=1
b[0][0]=1
print("#################")

print(a)
print("#####")
print(b)

The solution

My problem is why on array b all the values at the beginning of each lists gets replaced by 1 whereas not in array a. I need a geniune answer for it.

  • Does this answer your question? [Python array weird behavior](https://stackoverflow.com/questions/12995679/python-array-weird-behavior) – Abhinav Mathur Oct 31 '20 at 07:47

1 Answers1

0

When you do a b=[[0]*3]*3 it created a one d list of size three filled with zeros and then copies the same three times over. That is all of those three [0,0,0],[0,0,0],[0,0,0] refer to the same memory location. Hence when you update one a[0][0] = 1 it reflects in all three of them.

Contrary when you do a=[[0 for i in range(3)] for j in range(3)] this creates a unique mem location for each hence your updates are only reflected in one cell.

Also as the above comment pointed out this is a duplicate question.

Rahul
  • 895
  • 1
  • 13
  • 26