newbie : array initialization, anyone ?
Bjorn Pettersen
pbjorn at uswest.net
Wed Dec 27 16:19:36 EST 2000
arcege at shore.net wrote:
> Gerson Kurz <gerson.kurz at t-online.de> wrote:
> : you can initialize a fixed-size array using something like
>
> : array = [0] * 10
>
> : now, one would think that you can initialize a multidimensional array
> : like this:
>
> : multidim = [ [0] * 10 ] * 3
>
> : but now, all 3 elements in multidim are references to the same single
> : array, so that if you type
>
> : multidim[0][0] = 1
> : print multidim
>
> : you actually get three 1 in all those 0s. Where did my thinking go
> : wrong along these lines ?
>
> This is in the FAQ (#4.50). You will want to create each inner dimension
> individually:
>
> >>> multidim = [ None ] * 3
> >>> for i in range(3):
> ... multidim[i] = [ 0 ] * 10
> ...
> >>>
The FAQ should probably be changed to something like:
multidim = [ ([0] * 10) for i in range(3) ]
-- bjorn
More information about the Python-list
mailing list