0

I created a 2 dimensional list in python using c=[[0]*5]*3 and tried to update the value at c[1][4]=c[0][3]+1

but the value get updated at every 4th index of each row. I am not understanding why it happened?

>>> c=[[0]*5]*3

>>> c 

[[0, 0, 0, 0, 0] , [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

>>> c[1][4]=c[0][3]+1

>>> c 

[[0, 0, 0, 0, 1], [0, 0, 0, 0, 1], [0, 0, 0, 0, 1]]

while doing it using the for loop give the expected output

>>> a=[[0 for i in range(5+1)]for i in range(3+1)] 

>>> a

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]

>>> a[1][4]=a[0][3]+1
>>>a

[[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]
ZiGaelle
  • 744
  • 1
  • 9
  • 21
Gozo
  • 13
  • 5

1 Answers1

0

When you init c like this:

c=[[0]*5]*3

It is interpreted as such:

i = [0]*5
c = [i, i, i]

Which means that c is a list that is filled with a reference to the same object i.

So it doesn't matter which index of c you are accessing, it is actually the same instance (i).

In the second example:

a=[[0 for i in range(5+1)]for i in range(3+1)] 

You are creating a new list for every index of the list. So you get the expected output.

Liran Funaro
  • 2,750
  • 2
  • 22
  • 33