1

I need to create a 2x2x2x2 dimensional list in "pure" python, i,e, not using numpy.

Using numpy, I would simply write:

numpy.zeros((2,2,2,2))

In "plain python" I tried:

>>> aa=[[[[0]*2]*2]*2]
>>> aa
[[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]]

looks good, however

>>> aa[0][0][0][0]=1

results in:

>>> aa
[[[[1, 0], [1, 0]], [[1, 0], [1, 0]]]]

which is not what I want, of course

I always felt that this mutable object stuff in python was a strange design choice... anyway, is there a simple pythonic way to achieve what I want hopefully a one liner not requiring import(s). I understand that deep copying the list would fix the problem, but it is far from feeling elegant... :-)

user1159290
  • 951
  • 9
  • 27

1 Answers1

0

Try this:

>>> aa = [[[0 for _ in range(2)] for _ in range(2)] for _ in range(2)]

>>> aa
[[[0, 0], [0, 0]], [[0, 0], [0, 0]]]

>>> aa[0][0][0] = 1
>>> aa
[[[1, 0], [0, 0]], [[0, 0], [0, 0]]]
Selcuk
  • 57,004
  • 12
  • 102
  • 110