Re: How to do multi-dimensional arrays?

Aaron Watters (aaron@funcity.njit.edu)
Thu, 19 Jan 1995 14:11:59 GMT

The poster probably considered this obvious, but I didn't want any
newbies to be confused or distressed...

In article <3fkbij$mun@hustle.rahul.net> "Douglas K. Wyatt" <wyatt@rahul.net> writes:
>>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[1][2] = 42
> >>> arr
> [[0, 0, 42, 0], [0, 0, 42, 0], [0, 0, 42, 0], [0, 0, 42, 0]]
>...
The fix to avoid shared references is just a bit less elegant,
but not too bad:
>>> arr = [None]*4
>>> for i in range(4): arr[i] = [0]*4
...
>>> arr[1][2] = 42
>>> arr
[[0, 0, 0, 0], [0, 0, 42, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
Yours, not feeling like working right now, -a.
====
This is no movie! This is real!
Which real?
The third reel of this classic motion picture... (Firesign Theater)