Re: How to do multi-dimensional arrays?

Douglas K. Wyatt (wyatt@rahul.net)
19 Jan 1995 00:25:55 GMT

>Is there an elegant way to create a list containing N copies of
>one object?

Sure. [0]*4, for example, produces [0, 0, 0, 0].

Be careful, though:
>>> arr = [[0]*4]*4
>>> arr
[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
>>> arr[1][2] = 42
>>> arr
[[0, 0, 42, 0], [0, 0, 42, 0], [0, 0, 42, 0], [0, 0, 42, 0]]

The problem here is that arr contains four pointers to the same list object!

Here's a sketch of another approach:

class RectangularArray:
def __init__(self, rows, cols, value=0):
self.arr = [None]*rows
self.row = [value]*cols
def __getitem__(self, (i, j)):
return (self.arr[i] or self.row)[j]
def __setitem__(self, (i, j), value):
if self.arr[i]==None: self.arr[i] = self.row[:]
self.arr[i][j] = value

>>> arr = RectangularArray(5, 6)
>>> arr[(2, 3)] = 42
>>> print arr[(2, 3)], arr[(2, 4)], arr[(3, 3)]
42 0 0
>>> arr.arr
[None, None, [0, 0, 0, 42, 0, 0], None, None]

See chapter 3 of the Python Reference Manual for more information on
creating classes whose instances behave like sequence types.

>If you have to pass such an array to procedures, will you
>have a lot of copying overhead?

No. You're passing a reference.

>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]

-- 
Doug Wyatt | wyatt@rahul.net | http://www.rahul.net/wyatt/