How to add elements to 3 dimensional array in python

arrays, multidimensional-array, python

Solution

I recommend using `numpy` for multidimensional arrays. It makes it much more convenient, and much faster. This would look like:

import numpy as np
x = np.zeros((10,20,30)) # Make a 10 by 20 by 30 array
x[0,0,0] = value1

Still, if you don't want to use `numpy`, or need non-rectangular multi-dimensional arrays, you will need to treat it as a list of lists of lists, and initialize each list:

x = []
x.append([])
x[0].append([])
x[0][0].append(value1)

Edit: Or you could use the compact notation shown in ndpu's answer (`x = [[[value1]]]`).

Problem

I am trying to store data in three-dimensional array i.e, `x[0][0][0]` in Python. How to initialize `x`, and add values to it? I have tried this: ``` x=[] x[0][0][0]=value1 x[0][0].append(value1) ``` both lines are giving out of range error. How to do it? I want it like: `x[0][0][0]=value1`, `x[1][0][0]=value2`, `x[0][1][0]=value3` etc. How to achieve this in Python? I am looking to generate this kind of array: ``` x=[[[11,[111],[112]],[12],[13]],[[21,[211],[212]],[22],[23],[24]],[[31],[32]]] x[0][0][0] will give 11 x[1][0][0] 21 x[0][0][1] 111 ``` etc.

Original source