confused about adding elements to a list with list.append(otherlist)

James C. Ahlstrom jim at interet.com
Mon Aug 13 07:55:20 EDT 2001


Tist Verdonck wrote:

> my goal was to get the follwing value for list:
> [['ab','cd','de','ef','gh'],
> ['ab','cd','de','ef','gh','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ','IJ','IJ']]
>
> what I got is this:
> [['ab','cd','de','ef','gh','IJ','IJ','IJ','IJ','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ','IJ','IJ','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ','IJ','IJ','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ','IJ','IJ','IJ'],
> ['ab','cd','de','ef','gh','IJ','IJ','IJ','IJ','IJ']]

What you are seeing is the difference between "mutable" and "immutable"
objects in Python, an important difference.  Lists are mutable; they can be
changed.  Your code changes the original list and appends the same list
object over and over.  The same code, rewritten for tuples (which are
immutable) would work as you expect.

The fix is to use a copy of the list as in "newlist = oldlist[:]", or create a
new list object each time as in "newlist = oldlist " + "morestuff".

Jim Ahlstrom




More information about the Python-list mailing list