is this a bug or what?

Chris Liechti cliechti at gmx.net
Fri Dec 28 08:27:49 EST 2001


[posted and mailed]

"I.J." <shiver at yubc.net> wrote in news:a0dv4v$bnh$1 at cer.yubc.net:
>>>> M=[[0]*3]*3
>>>> M
> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>>> M[1][1]=1
>>>> M
> [[0, 1, 0], [0, 1, 0], [0, 1, 0]]
> 
> Is this new age math?

no your multiplying the reference to one list [0,0,0]. all three sublists 
are the same object.
it works well with strings, numbers and tuples because these are immutable 
an when you change someting a new object is generated.

e.g. 
l = [0]*4
l[2] = 1

a list like in your example can nicly be created by list comprehesions:
M = [ [0]*3 for i in range(3) ]

-- 
Chris <cliechti at gmx.net>




More information about the Python-list mailing list