1

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?

JolonB
  • 415
  • 5
  • 25
  • @GreenCloakGuy Somewhat. I suspect the `*2` operator might be creating a copy of the list reference, rather than a new list. If that's the case, any idea what the best way to initialise a multi-dimensional list is? – JolonB Aug 29 '20 at 02:33
  • 1
    To make a multi-dimensional list you'd probably want to use a list comprehension: `[[0] * 2 for _ in range(2)]` would work, since it re-evaluates the `[0] * 2` expression for every iteration. – Green Cloak Guy Aug 29 '20 at 02:34
  • @GreenCloakGuy Hey, you're right! I only need a 2D list. so this is exactly what I need, but surely this wouldn't work for any N-dimensional list unless I hardcode it for a given value of N (as in, N has to be constant, not variable) – JolonB Aug 29 '20 at 02:37
  • If you need to generate an arbitrary-sized list, I would use a recursive function to generate each layer at a time. – Green Cloak Guy Aug 29 '20 at 15:33

0 Answers0