1

I have the following code:

X = [[[None] * 4] * 2] * 6

for i in range(0, 6):
    X[i][0][0] = i

X

and the results gives:

[[[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]],
 [[5, None, None, None], [5, None, None, None]]]

This is very strange to me, shouldn't the result be like below ?

[[[0, None, None, None], [0, None, None, None]],
 [[1, None, None, None], [1, None, None, None]],
 [[2, None, None, None], [2, None, None, None]],
 [[3, None, None, None], [3, None, None, None]],
 [[4, None, None, None], [4, None, None, None]],
 [[5, None, None, None], [5, None, None, None]]]

What did I miss here? Thanks!

Edamame
  • 23,718
  • 73
  • 186
  • 320
  • 1
    Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – user3483203 Apr 12 '18 at 06:33
  • Use `[[[[None] for i in range(4)] for j in range(2)] for k in range(6)]` to create your list. You are just creating references to the same list atm. – user3483203 Apr 12 '18 at 06:36
  • Check the `id()` of container elements, you will see they are all the same list. – Chen A. Apr 12 '18 at 06:41

1 Answers1

0
a = [[]] * 2  # here initiated a list and assigned to a.
id(a[0]) >>> 4509460384
id(a[1]) >>> 4509460384

b = [[] for _ in range(2)]  # here constructing a list and assigning to b.
id(b[0]) >>> 4509626808
id(b[1]) >>> 4509626880

Hope this clears!

Amitkumar Karnik
  • 912
  • 13
  • 23