[ [ [] * y for y in range(3) ] * x for x in range(2) ]

Mel Wilson mwilson at the-wire.com
Thu Jan 30 15:46:41 CET 2003


In article <2vhh3v4ue9tsn5lgk6lpl7cd92i2s8fgh9 at 4ax.com>,
Chirayu Krishnappa <thephoenix235 at gmx.net> wrote:
>This is whats wrong.
>
>>>> L=[[[]]*3]*2
>>>> L
>[[[], [], []], [[], [], []]]
>>>> L[0][0]=1
>>>> L
>[[1, [], []], [1, [], []]]


Exactly.  To put it another way:

L = [ [[]]*3 ] * 2

is equivalent to

a = []
b = [a, a, a]
L = [b, b]

so that L[0] and L[1] refer to the same object -- and each
of the three items in that object refer to another unique
object.  Whatever you do to one, you do to the other(s), in
most cases.

   One thing that will break the symmetry is to assign
something different to either L[0] or L[1].  This is
effectively what all the other solutions do:  make sure that
the elements of L refer to different list objects from the
outset.

L[1] = [17]

or

L[1] = [[],[],[]]

for instance, would remove part of the problem by making
L[1] refer to a brand-new list object, although (assuming
`b`, used above, hasn't been re-bound in the meantime)

c = b
L[1] = c

would leave us right where we were before.


   It seems my post is just a long-winded way of avoiding
talking about references and PyObjects and the fact that the
effect of `=` is just to associate a name (in the form of a
character string) to a reference to an object, using some
particular dictionary.  Maybe it'll shed some light anyway.

        Regards.        Mel.




More information about the Python-list mailing list