# newbie : array initialization, anyone ?

Hamish Lawson hamish_lawson at yahoo.co.uk
Wed Dec 27 16:12:37 EST 2000

```    array = [0] * 10

multidim = [ [0] * 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.
The statement

multidim[0][0] = 1

is modifying the list multidim[0]; this list is the same one referred
to by multidim[1] and multidim[2], so they will reflect the change.

Likewise array[0] through array[9] 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[0] and have that change reflected in array[1]
through array[9]. (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 [0] * 10 you could do this (in Python 2.0):

multidim = [([0] * 10)[:] for i in range(3)]

or more efficiently:

zerolist = [0] * 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([0] * 10, 3)

Hamish Lawson

---------------------------

Gerson Kurz 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 ?
>

Sent via Deja.com
http://www.deja.com/

```