Re: How to do multi-dimensional arrays?

Ken Manheimer (klm@NIST.GOV)
Thu, 19 Jan 1995 10:07:50 -0500 (EST)

I would like to add a few refinements to doug's nice suggestions. One is
essentially cosmetic, while another makes for a substantial efficiency
improvement.

> >While I'm at it, is there a elegant way to remove the first
> >element of a list?
>
> Is this elegant enough?
> >>> xxx = [4,2,8,5,9]
> >>> yyy = xxx[0]; xxx=xxx[1:]
> >>> print yyy, xxx
> 4 [2, 8, 5, 9]

Firstly, i really like the elegance offered by python's composite-
assignment capability, a la djikstra:

yyy, xxx = xxx[0], xxx[1:]

Moreover, there is a better way to exclude the first element from a list,
if you're willing to alter the list's structure. Rather than popping off
the first element by copying over everything *but* the first element, you
can simply edit out the first element:

xxx[:1] = []

Ie, adapting it into the composite form, above:

yyy, xxx[:1] = xxx[0], []

(Note - slicing is great!)

Being curious about whether or not the python mechanisms optimize out the
difference, i ran a few cursory tests, and was not surprised to find that
the impact is substantial. On my machine, the alteration method is a
factor of from 3 to 5 times as fast (for lists of from 1000 to 10,000
elements, respectively) as doing the copying.

One other thing to mention, in passing. Encapsulating a multi-dimensional
array in a class object (as doug sketched with the RectangularArray
object) can be very powerful. In particular, you can implement fairly
efficient sparse or dense arrays, and i believe that you could efficiently
accomodate a wide range of densities with a single implementation, if you
are careful in your design...

Ken
ken.manheimer@nist.gov, x3539