0

I need an empty list with the following structure so I can later populate it without getting out of range errors:

[5[2[]]]

i.e.: [[[], []], [[], []], [[], []], [[], []]]

So I tried declaring it this way: [[[]]*n]*m / n=2, m=5

But * is copying references, so if i do something like this:

>>> foo = [[[]]*2]*5
>>> foo
   [[[], []], [[], []], [[], []], [[], []]]

>>> foo[3][0] = 1
>>> foo
   [[1, []], [1, []], [1, []], [1, []]]

The assigned value gets copied to all sub-lists with the same reference.

I can fix this by declaring foo's sizes "statically" like:

foo = [[[], []], [[], []], [[], []], [[], []]]

But I need a parametric way like the previous example.

I would like to know if there's a parametric pythonic/compact way of of declaring and empty list of lists (like with n and m in the example), where all its elements have individual references.

Thanks in advance!

lvisr
  • 3
  • 3
  • `[[] for _ in range(n)]` – Chris_Rands Apr 15 '20 at 10:14
  • 1
    Use a list-comp as mentioned in the dupe to create *new* lists at each position. In your case you should use `foo = [[[] for _ in range(2)] for _ in range(5)]` – yatu Apr 15 '20 at 10:17
  • Nice! that can work out this way: `foo = [[[] for _ in range(n)] for _ in range(m)]` Can you think of a more compact/readable version? – lvisr Apr 15 '20 at 10:19

0 Answers0