2D lists

Bengt Richter bokr at oz.net
Mon Jan 20 20:19:58 EST 2003


On 20 Jan 2003 11:06:47 -0800, marcin at finisar.com (Marcin Matuszkiewicz) wrote:

>In the code below I created a two dimensional list in two ways.  List
>b behaves I expect, list a does not.  Could someone explain it?
>
>>>> a=[[0]*4]*2
>>>> a
>[[0, 0, 0, 0], [0, 0, 0, 0]]
>>>> a[0][0]=1
>>>> a
>[[1, 0, 0, 0], [1, 0, 0, 0]]
>>>> b=[[0, 0, 0, 0], [0, 0, 0, 0]]
>>>> b[0][0]=1
>>>> b
>[[1, 0, 0, 0], [0, 0, 0, 0]]
>>>>

 >>> a=[[0]*4]*2
 >>> b=[[0, 0, 0, 0], [0, 0, 0, 0]]
 >>> map(id,a)
 [8220592, 8220592]
 >>> map(id,b)
 [8220640, 8224736]

I.e., the two sub-lists of a are references to the same list,
so the same list is being displayed twice like a = [same, same]
so if you make a change to same[0], (however you spell it --
you could write a[0][0] or a[1][0] and refer to the same slot in same)
it will show up in duplicate when a is represented.

b has separate sublists, as the id's show.

will show up
Regards,
Bengt Richter




More information about the Python-list mailing list