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?
The problem is that
* n
does a shallow copy of the list. A solution is to use nested loops, or try the numpy library.As others have mentioned, it's building the 2nd and 3rd levels with references, not clones. Try:
Or if you want to type a bit less:
If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:
It's not cloning the list. It's inserting a reference to the same list over and over. Try creating the list using a set of nested for loops.
I have to second what leonardo-santagada suggested, with the addition that creating N dimensional arrays/lists is very unpythonic and you should reconsider how you're keeping your data and seeing if it doesn't belong better in a class or a list of dictionaries (or dictionaries of lists).