List of lists surprising behaviour

Lie Ryan lie.1296 at gmail.com
Thu Jun 17 06:59:52 EDT 2010


On 06/17/10 20:21, candide 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)
>>>>

Yep, you're right. They share the same subarray if you uses
multiplication to build the array.

> 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)]

Right again. That's the way to go. Although if the elements are
immutable, you can create the innermost array by multiplication:

t=[[0]*2 for _ in range(3)]



More information about the Python-list mailing list