Bug or not ?

jay graves jgraves3 at austin.rr.com
Fri May 4 08:13:10 EDT 2001


On Fri, 04 May 2001 06:15:16 -0500, Changsen Xu <cxu1 at nd.edu> wrote:

>Hi all,
>I met a problem, not sure it's bug or not, same
>for Python version through1.5.2 to 2.0:
>>>> x= [ [0,0], [0,0] ]
>>>> x
>[[0, 0], [0, 0]]
>>>> x[0][0] = 1
>>>> x
>[[1, 0], [0, 0]]             ## This is exactly what I expect, same as
>C/C++
>
>>>> x = [ [0]*2 ] * 2
>>>> x
>[[0, 0], [0, 0]]
>>>> x[0][0] =1
>>>> x
>[[1, 0], [1, 0]]         ## This result differ from above
>
>
>Anybody can give me an explanation ? Thanks in advance.
>I was driven crazy to check my how-can-it-be-wrong
>tiny program dozens of times until I finally found the above
>difference!

No bug, maybe this will clarify what is going on.

>>> x =[[0]*2] * 2
>>> x
[[0, 0], [0, 0]]
>>> x[0]
[0, 0]
>>> id(x)
7937644
>>> id(x[0])
7936732
>>> id(x[1])
7936732
>>> id(x[0][0])
7745468
>>> id(x[0][1])
7745468
>>> id(x[1][0])
7745468
>>> id(x[1][1])
7745468
>>>

As you can see, x[0] and x[1] point to the same object and likewise 
x[a][b] where a = 0,1 and b = 0,1 are the same object.

I usually create this kind of construction using loops as opposed to
the * operator.  Hopefully one of the bots (or someone else) will jump
in and show us t.3.1est way to do this.

waiting-with-bated-breath-ly yrs
jay



More information about the Python-list mailing list