[Tutor] how to *really* copy a list

kevin parks kp8 at mac.com
Sun Apr 30 01:01:42 CEST 2006


Ed,

I should have realized that the nesting would create the problem, but i 
didn't have
that in mind... i always thought that the difference between extend and 
append
was that extend did not yield a nested list.

I really need to revisit this issue and get it right in my mind. It is 
a 'gotcha'
that i remember reading about often but, now that it has bit me a few 
times
hehe .... so much to know...

-kevin--



On Apr 29, 2006, at 6:00 AM, tutor-request at python.org wrote:

>>
>> Hi Kevin,
>>
>> Your problem is this line:
>>     seq.extend(foo)
>>
>> This is the line that mutates your original list.
>>
>> There are a few ways you could procede here.  One way is to make a
>> copy of the argument, like this:
>>
>> def mirror(seq):
>>     start = list(seq)
>>     end = seq[:-1]
>>     end.reverse()
>>     start.extend(end)
>>     return start
>>
>> Notice that we've not calling any methods on seq, so seq won't be
>> changed.  The first line, "start = list(seq)", instructs python to
>> build a new list out of the elements of seq.  You could also write
>> "start = seq[:]" here --- I'm not sure which is the preferred way.
>
> A little 'gotcha' with this is that if you have nested lists, these
> methods don't copy the nested lists, only the outer list (which makes
> sense, but can be surprising the first time you encounter it).  If for
> some reason you want to copy nested lists, look into deepcopy(),
> otherwise you'll be fine.



More information about the Tutor mailing list