[Tutor] Arrays

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Sun, 3 Sep 2000 00:41:03 -0700 (PDT)


> question, how can I define an array of classes or any other data type? I 
> don't think a list would work for me. Let me show you what i mean in c:
> 
> int myArray[5];
> 
> myArray[0] = 22;
> ...
> myArray[4] = 2;


Yes, you can use Python's lists to do this.  The thing you have to do is
initialize the list to be long enough.  For example, you probably ran into
the problem of IndexError's popping up:


###
>>> myArray = []
>>> myArray[0] = 22
Traceback (innermost last):
  File "<stdin>", line 1, in ?
IndexError: list assignment index out of range
###


This is because 'myArray = []' doesn't quite capture the idea of 
'int myArray[5];'.  At the very least, we need our myArray to hold 5
elements.  This isn't too hard to fix, though.  Take a look:


###
>>> myArray = [0] * 5    # Initialize myArray to a list of 5 zeros
>>> myArray
[0, 0, 0, 0, 0]
>>> myArray[0] = 22
>>> myArray
[22, 0, 0, 0, 0]
###


I'm not sure if it's the Pythonic way of doing things; there may be a more
idiomatic way of sizing the list.  However, '[0] * length' seems to be
sufficient for many casual cases, and it's nicer because we can still do
things like append() or insert() with our lists.  Furthermore, the list is
still heterogeneous --- we can put numbers, or strings, or whatever we
want in that list, and it will still work.


###
>>> myArray[4] = ('Ruronin', 'Kenshin')
>>> myArray
[22, 0, 0, 0, ('Ruronin', 'Kenshin')]
###


If you really need efficient arrays, you might want to look at Numerical
Python, which is a module that's specialized for very fast and lightweight
arrays and matrices:

    http://numpy.sourceforge.net/


Good luck!