newbie : array initialization, anyone ?
hamish_lawson at yahoo.co.uk
Wed Dec 27 16:12:37 EST 2000
array =  * 10
multidim = [  * 10 ] * 3
It should be noted that *both* 'array' and 'multidim' are lists that
consist of references to the same respective single object; in the case
of 'multidim' that shared object is the list object [0, 0, 0, 0, 0, 0,
0, 0, 0, 0], while in the case of 'array' that shared object is the
integer object 0.
A list can be modified and all references to it will see that change.
multidim = 1
is modifying the list multidim; this list is the same one referred
to by multidim and multidim, so they will reflect the change.
Likewise array through array refer to the same object, the
integer 0. *If* there were operations available that allowed you to
modify integers, then it would be possible to modify the object
referred to by array and have that change reflected in array
through array. (But of course Python doesn't provide operations to
modify integers, since it wouldn't make sense to be able to change the
zeroness of 0 - though of course Python does provides operations for
producing integers from other integers, e.g. 2 + 3).
To get independent copies of  * 10 you could do this (in Python 2.0):
multidim = [( * 10)[:] for i in range(3)]
or more efficiently:
zerolist =  * 10
multidim = [zerolist[:] for i in range(3)]
or also more generally:
def duplist(a, n=1):
return [a[:] for i in range(n)]
multidim = duplist( * 10, 3)
Gerson Kurz wrote:
> you can initialize a fixed-size array using something like
> array =  * 10
> now, one would think that you can initialize a multidimensional array
> like this:
> multidim = [  * 10 ] * 3
> but now, all 3 elements in multidim are references to the same single
> array, so that if you type
> multidim = 1
> print multidim
> you actually get three 1 in all those 0s. Where did my thinking go
> wrong along these lines ?
Sent via Deja.com
More information about the Python-list