List of lists surprising behaviour

J Kenneth King james at agentultra.com
Thu Jun 17 16:25:53 EDT 2010


candide <candide at free.invalid> writes:

> Let's the following code :
>
>>>> t=[[0]*2]*3
>>>> t
> [[0, 0], [0, 0], [0, 0]]
>>>> t[0][0]=1
>>>> t
> [[1, 0], [1, 0], [1, 0]]
>
> Rather surprising, isn't it ? 

Not at all, actually.

I'd be surprised if the multiplication operator was aware of object
constructors.  Even arrays are "objects" in Python.  Should the
multiplication operator know how to instantiate three arrays from a
single array instance?  What about an instance of a user-defined class?

> So I suppose all the subarrays reférence
> the same array :
>
>>>> id(t[0]), id(t[1]), id(t[2])
> (3077445996L, 3077445996L, 3077445996L)
>>>>
>

As they should.

>
> So what is the right way to initialize to 0 a 2D array ? Is that way
> correct  :
>
>
>>>> t=[[0 for _ in range(2)] for _ in range(3)]
>
> It seems there is no more trouble now :
>
>>>> t
> [[0, 0], [0, 0], [0, 0]]
>>>> t[0][0]=1
>>>> t
> [[1, 0], [0, 0], [0, 0]]
>>>>
>
> Correct ?

>>> 2d_zero_vector = lambda len: [[0, 0] for _ in range(len)]
>>> t = 2d_zero_vector(3)
>>> print t
[[0, 0], [0, 0], [0, 0]]
>>> t[0][0] = 1
>>> print t
[[1, 0], [0, 0], [0, 0], [0, 0]]

(Of course, if you're doing matrix math you'll probably want to work
with numpy which has a function for doing just this)



More information about the Python-list mailing list