1

I created a list of lists like this

In [1]: list_of_list = [ [0] * 4]* 4
In [2]: list_of_list

Out[2]: [[0, 0, 0, 0], 
         [0, 0, 0, 0], 
         [0, 0, 0, 0],
         [0, 0, 0, 0],]

And when I assign a value to the element in this list_of_list it assigns it to a column of elements.

In [3]: list_of_list[2][3]
Out[3]: 0

In [4]: list_of_list[2][3] = 1

In [5]: list_of_list
Out[5]: [[0, 0, 0, 1], 
         [0, 0, 0, 1], 
         [0, 0, 0, 1], 
         [0, 0, 0, 1],]

Why python behave like this ?

Thank you.

Rahul K P
  • 15,740
  • 4
  • 35
  • 52

1 Answers1

4

This operation:

[0] * 4

Creates a list of four zeros. This is fine, each is copied by value in python since numbers less than 255 are effectively treated as "primitives".

However,

list_of_list = [[0, 0, 0, 0]]* 4

Copies the list by reference. Anything that happens to one of these lists happens to all of them.

Leb
  • 15,483
  • 10
  • 56
  • 75
KeatsKelleher
  • 10,015
  • 4
  • 45
  • 52