Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 806
Matt Boehm Avatar asked May 21 '26 04:05

Matt Boehm


2 Answers

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

like image 196
Tordek Avatar answered May 26 '26 21:05

Tordek


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
like image 39
Leonardo Santagada Avatar answered May 26 '26 21:05

Leonardo Santagada