Novice [].append Help

John Roth newsgroups at jhrothjr.com
Mon Mar 1 20:20:35 EST 2004


"waters" <waters at porkless.net> wrote in message
news:c20iig08ip at enews1.newsguy.com...
> I seem to have hit a snag.
>
> I am trying to add the list (l_local) as an item in the output list
> (l_output). "l_local" is a modified copy of the format-list "l_format",
> which will be updated by index position within the function. The problem
> occurs in the following statement block:
>
> def create_apid_list(l_format,l_values):
>      l_output = []
>      for t_curr_line in l_values: # ...for each list in the values list
>          l_local = l_format # ...assign blank format to local list
>          l_local[0] = t_curr_line[0] # ...modify with vendor number
>          l_local[1] = t_curr_line[1] # ...modify with invoice number
>          # print l_local # ... for testing
>          l_output.append(l_local) # ...add list as item to output list
>       return l_output
>
> ...the "l_output.append(l_local)" line is not returning the expected
> result. It is correctly producing a list of lists, but they all contain
> the the same values from the last t_curr_line[0] & t_curr_line[1]
> records in the l_values list. The preceding print statement displays the
> proper values containing data from all of the lists in l_values, so I'm
> not sure what the problem is.

You've fallen into one of the little traps. There's only *one*
copy of the l_format list, and it's being bound to l_local each
time through the loop. Assignment is *not* creating a copy of
the l_format list; it's reusing it, so each slot in the l_output list
is pointing to the *same* list, which of course contains the last
value you put into it.

If you change the 4th line to:

l_local = list(l_format)

it will work because the list type will produce a copy.

John Roth





More information about the Python-list mailing list