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

Alex Martelli aleaxit at yahoo.com
Mon Aug 13 07:35:31 EDT 2001


"Tist Verdonck" <tist.verdonck at mailandnews.com> wrote in message
news:8e84aae6.0108130241.2163205c at posting.google.com...
> I got this problem where I have an empty list and I want to fill it up
> with other lists using a for-iteration:
>
> list = []
> data = ['ab','cd','de','ef','gh']
> z = len(data)
> for x in range(z):
>     list.append(data)
>     data.append('IJ')
>
> my goal was to get the follwing value for list:
> [['ab','cd','de','ef','gh'],
> ['ab','cd','de','ef','gh','IJ'],

So, you want list (bad name, as it's the name of a builtin, but OK) to
contain,
not data itself, but rather "snapshots", i.e., COPIES, of what data held at
the
time it was appended, right?

So, just ask explicitly for a copy when you DO want a copy:
NOT
    list.append(data)    # this appends data itself
BUT
    list.append(data[:]) # this appends a COPY of data

The ...[:] full-list-slice makes a copy, but a more general approach would
be
to
    import copy
and then ask for
    list.append(copy.copy(data))
This makes it clearer that a copy is being requested, and therefore seems
more readable and advisable.  But it's up to you, of course.


Alex






More information about the Python-list mailing list