Multidimensional arrays - how?

Jeff Shannon jeff at ccvcorp.com
Fri May 3 13:48:13 EDT 2002


(I haven't received the original article, so I'm replying to this 
reply to it...)

> "Jaros³aw Zabie³³o" <webmaster at apologetyka.com.pl (delete .PL)> wrote in
> message news:6vv4du8mu1hj59k7g0uq58r24mp74g02hu at 4ax.com...
> > 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'

In Python, if you want to do this, you have to explicitly create 
the nested list yourself.  The following will work:

>>> book, chapter, para = 0, 0, 0
>>> x = [ [ ['para0', 'para1'] ] ]
>>> x[book][chapter][para]
'para0'
>>> x[book][chapter]
['para0', 'para1']
>>> 

Note that x[book][chapter] evaluates to a list; 
x[book][chapter][para] then indexes into *that* list.  And 
similarly, x[book][chapter] is indexing into the list referred to 
by x[book], which is indexing into the list referred to by x.

Hope this explains how this works a bit better, for you.  This 
being said, it's likely that you're better off using the 
dictionary idea in this case, but it's good to know how nested 
lists work anyhow.  :)

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list