Bug or not ?
Steve Holden
sholden at holdenweb.com
Fri May 4 08:08:07 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!
>
The puzzling aspect of this question comes about because
x = [ [0]*2 ] * 2
gives you a list containing two references to the same [0]*2. This has been
discussed before, but it's a common thing for Python starters to stumble
over. The correct way to overcome the problem is to build your lists
dynamically, rather than using the * operator.
I should have thought there would be a FAQ entry about this, but I don't see
one -- anyone?
regards
Steve
More information about the Python-list
mailing list