From: dacut at kanga.org (David Cuthbert)
Date: Fri, 23 Apr 1999 20:32:41 -0400
Subject: Bug or Feature?
References: <37208E69.4B022E0C@mediaone.net>
Message-ID: <7fr3eg$bqr@world1.bellatlantic.net>
X-UID: 152                                                  

Fuming Wang <fmwang at mediaone.net> wrote:
> I found this little surprise with Python 1.5.1:
> >list = [[0]*2]*4
> >list
> [[0, 0], [0, 0], [0, 0], [0, 0]]
> >list[0][1] = 9
> >list
> [[0, 9], [0, 9], [0, 9], [0, 9]]

> Is this a bug or a feature that I don't know about?

Most definitely a feature.  You're getting the same reference for all four
list elements.  To break it apart:

list = [[0] * 2] * 4       # let a = 0, an integer.
       [[a] * 2] * 4       # integers are immutable, so a copy is made
                           # for [a] * 2; let the copy be b.
       [[a, b]] * 4        # ah, but [a, b] is a list, q.
       [ q ] * 4           # lists are mutable, so we're just expanding
                           # references that all refer to the same
                           # q object.
       [ q, q, q, q ]      # Ta da!  All four elements have the same
                           # object.

If this were not the case, lists would be completely unnecessary since they
would be the same as tuples!







