# Create 3D array using Python

### Question

I would like to create a 3D array in Python (2.7) to use like this:

``````distance[i][j][k]
``````

And the sizes of the array should be the size of a variable I have. (n*n*n)

I tried using:

``````distance = [[[]*n]*n]
``````

but that didn't seem to work.

Any ideas? Thanks a lot!

EDIT: I can only use the deafult libraries, and the method of multiplying (ie [[0]*n]*n) wont work because they are linked to the same pointer and I need all of the values to be individual

EDIT2: Already solved by answer below.

1
33
5/19/2012 8:33:33 PM

### Accepted Answer

You should use a list comprehension:

``````>>> import pprint
>>> n = 3
>>> distance = [[[0 for k in xrange(n)] for j in xrange(n)] for i in xrange(n)]
>>> pprint.pprint(distance)
[[[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]]]
>>> distance[0][1]
[0, 0, 0]
>>> distance[0][1][2]
0
``````

You could have produced a data structure with a statement that looked like the one you tried, but it would have had side effects since the inner lists are copy-by-reference:

``````>>> distance=[[[0]*n]*n]*n
>>> pprint.pprint(distance)
[[[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]]]
>>> distance[0][0][0] = 1
>>> pprint.pprint(distance)
[[[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]]]
``````
58
5/20/2012 2:08:50 AM

`numpy.array`s are designed just for this case:

`````` numpy.zeros((i,j,k))
``````

will give you an array of dimensions ijk, filled with zeroes.

depending what you need it for, numpy may be the right library for your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon