troubles with list.append()

Alex Martelli aleaxit at yahoo.com
Sat Sep 8 22:32:29 CEST 2001


Joe wrote:

> I'm having some difficulties with appending
> a list to a list.  The code works how I want
> it to if used within the the interpreter.

You're probably doing something slightly different in that case.

> patch_listing.append(patch)
> 
> Printing patch_listing after the while loop
> shows it filled with all of the same entries.

Right, because you ARE appending references that are all to the same 
object, patch.  Append *copies* of that obiect instead, e.g.:

        patch_listing.append(patch[:])

or, after an import copy,

        patch_listing.append(copy.copy(patch))

Python never implicitly takes a copy -- you have to request one when you 
want one.  That doesn't matter for immutable objects, but lists are 
mutable, so there IS a difference between having a copy (a "snapshot" taken 
at some point, and fixed unless and until you choose to mutate it) and a 
reference to the original (since the "original" object keeps changing).


Alex




More information about the Python-list mailing list