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?