Bug or Feature?

David Cuthbert dacut at kanga.org
Fri Apr 23 20:32:41 EDT 1999


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!







More information about the Python-list mailing list