Bug or not ?

PoD pod at internode.on.net
Fri May 4 15:51:14 EDT 2001


Gerald Osmann wrote:
> 
> "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

I was bitten by this one early on as well.
Is there a reason for the current behaviour being desirable?
[[0]*height]*width seems like an obvious way to make a 2D array.

PoD



More information about the Python-list mailing list