13

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.

5
  • Make x three dimensional first. Commented Mar 16, 2013 at 11:20
  • It's not a 3-dimensional array, it's a list of lists of lists. If you want to work with it you need to do all work manually. Commented Mar 16, 2013 at 11:24
  • @lokesh creating all intermediate lists Commented Mar 16, 2013 at 11:34
  • Oh... just look at the answers below ;) Commented Mar 16, 2013 at 11:45
  • lokesh, there have been some good answers here. If the result is still not clear, you probably need to do some python tutorials. Here is one I googled from Think Python Commented Mar 16, 2013 at 12:15

7 Answers 7

31

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]]]).

Sign up to request clarification or add additional context in comments.

6 Comments

buses[0]=[] IndexError: list assignment index out of range.. i am not interested to use numpy. with out numpy how to do?
@lokesh you cannot assign values to items that don't exist. Please read how to work with lists in Python.
@lokesh: I was a bit too quick with my initial answer. I have edited it now. Why don't you want to use numpy, by the way?
i can use that. but how can i initialize not as fixed array. i mean i dont know my array size at first.
In cases like that, I usually append all elements to a one-dimensional, flat list, and then, when I am finished reading, convert it to a numpy array and reshape it to the correct, three-dimensional shape. I.e. something like a = np.array([float(word) for line in file for word in line]); a = np.reshape(a, (a.size/10,10)). But of course, there is nothing wrong with building up the full multidimensional list first, and then converting it to an array.
|
7

If you are creating some 3D sparse array, you can save all the data in a dict:

x={}
x[0,0,0] = 11
x[1,0,0] = 21
x[0,1,1] = 111

or:

from collections import defaultdict
x = defaultdict(lambda :defaultdict(lambda :defaultdict(int)))

x[0][0][0] = 11
x[1][0][0] = 21
x[0][0][1] = 111

4 Comments

i want something mutable. x={} i can't set item to it.
What is "x={} i can't set item to it" means?
in your suggestion i want to remove x[0,0,0]. how can i remove once x created.
in you example the len(x) is three. how can i access each one based on this index. for example x(1) should give 11. respectively.
3

If you can use numpy, you can initialize a fixed size array as:

import numpy
x = numpy.zeros((i, j, k))

where i, j and k are the dimensions required.

You can then index into that array using slice notation:

x[0, 0, 0] = value1
x[1, 0, 0] = value2

1 Comment

my array size is not fixed. can i initialize variable size
3

I just came up with this, it's more dynamic and simple.

# Define how large to make the object.
size = 3

# Build the three dimensional list.
memory = []
for x in range(0,size):
    memory.append([])
    for y in range(0,size):
        memory[x].append([])
        for z in range(0,size):
           memory[x][y].append(0) # Fill with zeros.

# Iterate through all values.
for x in range(0,size):
    for y in range(0,size):
        for z in range(0,size):
            print 'memory[' + str(x) + '][' + str(y) + '][' + str(z) + ']=' + str(memory[x][y][z])

# Example access.
print 'Example access:'
print 'memory[0][1][2]=' + str(memory[0][1][2])

Output:

memory[0][0][0]=0
memory[0][0][1]=0
memory[0][0][2]=0
memory[0][1][0]=0
memory[0][1][1]=0
memory[0][1][2]=0
memory[0][2][0]=0
memory[0][2][1]=0
memory[0][2][2]=0
memory[1][0][0]=0
memory[1][0][1]=0
memory[1][0][2]=0
memory[1][1][0]=0
memory[1][1][1]=0
memory[1][1][2]=0
memory[1][2][0]=0
memory[1][2][1]=0
memory[1][2][2]=0
memory[2][0][0]=0
memory[2][0][1]=0
memory[2][0][2]=0
memory[2][1][0]=0
memory[2][1][1]=0
memory[2][1][2]=0
memory[2][2][0]=0
memory[2][2][1]=0
memory[2][2][2]=0
Example access:
memory[0][1][2]=0

Comments

2
>>> x=[[[[]]]]
>>> x[0][0][0]=0
>>> x
[[[0]]]
>>> x[0][0].append(1)
>>> x
[[[0, 1]]]

Comments

1

A compilation of techniques above with respect to effectively creating a two-dimensional dict is:

from collections import defaultdict
x = defaultdict(lambda :defaultdict())
x["a"]["b"] = 123
x["a"]["c"] = 234
x["b"]["a"] = 234    
x["b"]["c"] = 234    
x["c"]["a"] = 234
x["c"]["b"] = 234
for i in x: 
    for j in x[i]: print i, j, x[i][j]

Produces:

a c 234
a b 123
c a 234
c b 234
b a 234
b c 234

To increase the number of dimensions (e.g., to three-dimensions), simply increase the lambda "nest" as HYRY shows:

x = defaultdict(lambda :defaultdict(lambda :defaultdict(int)))

Comments

0

Interator. I use function lambda for create matrix with [ [ 0 for j in range(n)] for i in range(m) ] in python 3. In the version 2 a used map functions. In this moment think like use array module (pure python) to create matrixes.

>>> arr = lambda m,n,l : [ [ [0 for k in range(l)] for j in range(n)] for i in range(m) ]
>>> m = arr(2,3,4)
>>> m
    [[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.