Bug or not ?

Gerald Osmann Gerald.Osmann at sap.com
Fri May 4 07:36:54 EDT 2001


"Changsen Xu" <cxu1 at nd.edu> wrote in message
news:3AF28F44.EF9318FE at nd.edu...
> 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!
>
>

Hi Changsen,
in the second example the two sublists refer to the same object. For list L
L*2 is different vom [L]*2.
Look into the data structure chapter of "Learning Python" for just this
problem.
Best wishes, Gerald





More information about the Python-list mailing list