0

I was working with some 2d data, where the data could be of different types. For ease of use, I opted for 2d lists.
Since the sizes were fixed, I tried to initialise a fixed 2d list using multiplication, like the code below:

list2d = [[None] * size] * size

Now, when I try to populate any row, col in the list, all rows are just copies(reference) of a single 1d list. (if that makes sense)

Sample code and output below:

list2d = [[None] * 4] * 4
for i in range(len(list2d)):
    list2d[i][i] = 42
print(list2d)

Output:

[[42, 42, 42, 42], [42, 42, 42, 42], [42, 42, 42, 42], [42, 42, 42, 42]]

So, my questions are thus:

  • What is happening over here?
  • Is each row a reference to a 1d list?
  • What are some alternatives to declaring 2d list effectively?
biplobmanna
  • 441
  • 5
  • 8
  • I am pretty sure, that this question is duplicate :) but I tried to answer anyway, you can reseach more info later. – mikulatomas Jan 27 '22 at 16:32

1 Answers1

2

The problem is that [None] * size inside list2d = [[None] * size] * size is created only once and reference is duplicated, so you have size times same structure created once by [None] * size.

I would suggest you to use list comprehesion:

list2d = [[None] * size] for _ range(size)]

That ensures that each [None] * size] will be created (and stored) as separated value.

mikulatomas
  • 330
  • 1
  • 12