My first stumbling block with Python

Terry Hancock hancock at
Fri Aug 23 11:24:39 CEST 2002

Going back to the original problem -- I've been wracking
my brain trying to think of an example problem in which
it would be *useful* to have a 2-D array of tuples. :-O

If the tuples were equal-sized objects with number contents,
it would probably be much more efficient to simply use
a 3-D Numeric array to represent the data. Presumeably
that isn't what you're storing, though?  (If it is, you
should get a big speed-up -- worth the overhead of
loading tuples into the array, I would think).

Are the tuples different sizes, or have non-numerical
content?  What kind of look-up efficiency are we
concerned about?  Or are you more concerned about 
code readability?

Would it perhaps be meaningful to simply define a
dictionary with 2-tuple indexes:

arraydata = {}

arraydata[(53, 32)] = ('a', 'b', 'c')
arraydata[(1, 41)]  = ('a', [23, 45], 'q')


I'm not sure about performance, but surely 2-tuples hash
well (?).  Of course, you'd have to beware of unassigned
cells, but that's true for an array too. (I believe there
is a good idiom for substituting a default value, which
would provide a smart sparse-array solution, if that's
what you have).

If the tuples are complex numbers, BTW, I'm fairly sure
that Numeric or one of the other extension modules will
give you those as intrinsic types (I haven't looked it
up, though).

It would be cool if you could share something more about
the problem -- my curiosity is piqued.

From: Greg Ewing <see_reply_address at something.invalid>
> Mr. Neutron wrote:
> > The answer is
> >       MyArray = [ [0]*512 for i in range(512) ]
> > 
> > I found this to be really peculiar and hard to understand.
> It might help to see it re-written without
> a list comprehension:
>    MyArray = []
>    for i in range(512):
>      MyArray.append([0]*512)

I hate to say it, but this is an argument against having
list comprehensions, isn't it? (i.e they save space, but
then you have to explain them).  Hmm.


Terry Hancock
hancock at       
Anansi Spaceworks         
P.O. Box 60583                     
Pasadena, CA 91116-6583

More information about the Python-list mailing list