List of lists surprising behaviour

candide candide at free.invalid
Thu Jun 17 06:21:31 EDT 2010


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 ?



More information about the Python-list mailing list