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.
If you want to do numerical processing with 3-d matrix you are better of using numpy. It is quite easy:
>>> import numpy
>>> numpy.zeros((3,3,3), dtype=numpy.int)
array([[[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]]])
>>> _[0,0,0]
0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With