I've created a 2D list in Python but when I assign values to it, it will assign the same value in all rows.
It's easier to show with an example. I have two 2D lists which will be 2x2 for the sake of simplicity. One of these lists will show the expected behaviour and the other will show the problematic behaviour.
>>> list_good = [[0, 0], [0, 0]]
>>> list_bad = [[0]*2]*2
First, we can check that both of these are the same:
>>> list_good == list_bad
True
The issue arises when assigning data to the list:
>>> list_good[1][1] = 1
>>> list_good
[[0, 0], [0, 1]]
>>> list_bad[1][1] = 1
>>> list_bad
[[0, 1], [0, 1]]
Both lists are the same, but the output of them is dependent on how they are initialised. So what's happening here?
I want to access the list through indexing (rather than using .append()), so I need to initialise it beforehand. What would be the most Pythonic way to fix this?