2D lists

Byron Morgan lazypointer at yahoo.com
Tue Jan 21 02:57:45 EST 2003


a is a tuple with one list object, referenced twice.
b is a tuple with two list objects.

id() makes it clear:

>>> a=[[0]*4]*2
>>> a
[[0, 0, 0, 0], [0, 0, 0, 0]]
>>> id(a[0])
24149152
>>> id(a[1])
24149152
>>>
>>> b=[[0, 0, 0, 0], [0, 0, 0, 0]]
>>> id(b[0])
24146560
>>> id(b[1])
24158720
>>>

"Marcin Matuszkiewicz" <marcin at finisar.com> wrote in message
news:c7486c63.0301201106.681eece8 at posting.google.com...
> 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]]
> >>>
>
> Thanks,
>
> Marcin






More information about the Python-list mailing list