List of lists surprising behaviour

Matteo Landi landimatte at gmail.com
Thu Jun 17 07:11:25 EDT 2010


Yes you are. List comprehension makes you create list of lists without
reference-sharing. You should also find a recipe about that on the
python cookbook.

On Thu, Jun 17, 2010 at 12:21 PM, candide <candide at free.invalid> wrote:
> 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 ? So I suppose all the subarrays reférence the
> same array :
>
>>>> id(t[0]), id(t[1]), id(t[2])
> (3077445996L, 3077445996L, 3077445996L)
>>>>
>
>
> 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 ?
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/



More information about the Python-list mailing list