Is it possible to specify the size of list at construction?

Terry Hancock hancock at anansispaceworks.com
Wed Mar 2 01:18:39 EST 2005


On Tuesday 01 March 2005 02:50 pm, Anthony Liu wrote:
> Yes, that's helpful.  Thanks a lot.
> 
> But what if I wanna construct an array of arrays like
> we do in C++ or Java:
> 
> myArray [][]
> 
> Basically, I want to do the following in Python:
> 
> myArray[0][1] = list1
> myArray[1][2] = list2
> myArray[2][3] = list3
> 
> How to do this, gurus?

One answer is "don't".  You might for example, use a 
dictionary with 2-tuple keys:

dict = {  (a,b): value1, (c,d):value2, ...}

this has some advantages over an array approach,
including the fact that you immediately can model
a sparsely-sampled domain (or one with non-integral
and/or unevenly spaced sampling points).

Filling such a dictionary evenly isn't hard:

data = {}
for i in range(20):
  for j in range(10):
      data[(i,j)] = your_func(i,j)

Accessing it might be a little dicey if you want to allow
for filling holes:

f = data.get( (i,j), 0)

(will return 0 if no value exists at (i,j)).


If you really do need a filled array of any size, though,
you probably don't want to use lists or dictionaries, but
actual *arrays* like those provided by the Numeric or
Numarray modules (these are scientific programming
extension modules for Python -- actually two implementations
of the same concept, with nearly identical usage, but 
slightly different performance.


--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list