Search code examples
pythonlistmutable

Problem creating N*N*N list in Python


I'm trying to create a 3-dimensional NNN list in Python, like such:

n=3
l = [[[0,]*n]*n]*n

Unfortunately, this does not seem to properly "clone" the list, as I thought it would:

>>> l
[[[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0], [0, 0, 0]]]
>>> l[0][0][0]=1
>>> l
[[[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]], [[1, 0, 0], [1, 0, 0], [1, 0, 0]]]

What am I doing wrong here?


Solution

  • The problem is that * n does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.