copy a list

phil hunt philh at cabalamat.org
Mon Mar 10 08:55:11 EST 2003


On Mon, 10 Mar 2003 08:12:18 GMT, Alex Martelli <aleax at aleax.it> wrote:
>Yuval wrote:
>
>> Hi,
>> I have to work on a list without changing it. Specifically, in every
>> iteration I have to choose an object and remove it in the end of that
>> iteration, repeat it until the list is empty. However, I do not want
>> to touch the list itself since I need to repeat this process many
>> times (start over again once the list is empty). Therefore, in order
>> to "play around" with a list A, I create a copy of it: B = A[:].
>> My problem is that it slows down my program siginificantly. Is it a
>
>The copy operation, whether you perform it in the usual way you have
>written or in the equivalent and more readable way B = list(A), is
>_EXTREMELY_ unlikely to account for any significant slice of your
>program's running time.  The copy itself takes time k * len(A) for
>a reasonably small constant k; then after each copy you _repeatedly_
>"choose an object", then "remove it" -- an operation that's most
>likely K * len(B) for some K > k -- repeatedly until len(B) goes
>down to 0 -- which suggests that part must take time proportional
>to the SQUARE of len(A) [sum of 1, 2, ..., N is proportional to
>the square of N).

This is a good point. Python comes with a profiler -- perhaps the 
original poster would like to use it and see what figures he comes 
back with.

-- 
|*|*|  Philip Hunt <philh at cabalamat.org>  |*|*|
|*|*|  "Memes are a hoax; pass it on"     |*|*|





More information about the Python-list mailing list