Novice [].append Help

Jeff Epler jepler at unpythonic.net
Mon Mar 1 20:17:10 EST 2004


First a gripe about your code: the l_ stuff is painful to read.

Anyway, the line
    l_local = l_format
merely makes l_local a reference to the same thing as l_format (l_local
is l_format).  The next two lines change some of the elements in that
list, and then l_output gets another reference to the same list added to
it.  It's no surprise, then, that all of l_output's items are equal when
the function is done: it's a list containing many references to the same
thing.

This may do what you want if you change that line to
    l_local = l_format[:]
seq[:] is a slice including all the elements of seq, and is a very
common shorthand for making a shallow copy.  You could also write
    l_local = t_curr_line[:2] + l_format[2:]
to assemble l_local from slices of other lists.

Here's how I'd be tempted to write your function:

    def create_apid_list(format, values):
        return [ v[:2] + format[2:] for v in values ]

or, if the context allows for the use of an iterator and you're using
Python 2.3:

    def create_apid_list(format, values):
        for v in values:
            yield v[:2] + format[2:]

Jeff




More information about the Python-list mailing list