Arrays have a fixed size. You can't append to them. If you know the upper bounds of the array, you can preallocate the array with
np.empty((10, 10, 10))
For a 10x10x10 matrix. You can then keep 3 indices x,y,z to track the actual size you have. Eg, add a new element with:
matrix[x,y,z] = newElement
x += 1
Then when you're done, you can extract the submatrix with
finalMatrix = matrix[:x,:y,:z]
Answer from Oren Bell on Stack OverflowArrays have a fixed size. You can't append to them. If you know the upper bounds of the array, you can preallocate the array with
np.empty((10, 10, 10))
For a 10x10x10 matrix. You can then keep 3 indices x,y,z to track the actual size you have. Eg, add a new element with:
matrix[x,y,z] = newElement
x += 1
Then when you're done, you can extract the submatrix with
finalMatrix = matrix[:x,:y,:z]
You can use np.empty((x,y,z))
You can find a good explanation in this answer: How to create 3 dimensions matrix in numpy , like matlab a(:,:,:)
I'd suggest using np.full_like to choose the fill-value directly...
x = np.full_like((3, 1), None, dtype=object)
... of course the dtype you chose kind of defines what you mean by "empty"
I am guessing that by empty, you mean an array filled with zeros.
Use np.zeros() to create an array with zeros. np.empty() just allocates the array, so the numbers in there are garbage. It is provided as a way to even reduce the cost of setting the values to zero. But it is generally safer to use np.zeros().
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]]]
numpy.arrays 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.