Multidimensional arrays - how?

Jeff Davis jdavis at empires.org
Fri May 3 15:31:37 EDT 2002


x = []
x.append([])
x[0].append([])
x[0][0].append([])
x[0][0][0].append('text0')

Hmm... doesn't look to graceful though. It seems as though that style 
works out for most common situations where you add one element at a time.

If you want a preallocated array try the following
x = [None for foo in range(0,5)]
# gives x[5]
or even:
x = [[None for foo in range(1,5)] for foo in range(0,5)]
# the above givies you an array like x[5][5]

I hope that works out for you. It might seem a little messier than what 
you're used to. However, I think it help to keep good track of variables 
like this. There also might be a better way that I don't know of.

Jeff Davis

Jaros³aw Zabie³³o wrote:

> How to create multidimmensional arrays in Python? I tried:
> 
> x = []
> 
> book, chapter, para = 0,0,0
> x[book][chapter][para] = 'text0'
> 
> book, chapter, para = 0,0,1
> x[book][chapter][para] = 'text1'
> 
> This code does not work in Python :-( but (with slightly changings)
> works in PHP, C, C++ or Pascal).
> 
> --
> Jaros?aw Zabie??o (UIN: 6712522)
> URL: http://3585753410/~zbiru






More information about the Python-list mailing list