[Tutor] 2 problems in a small script

Kent Johnson kent37 at tds.net
Fri Oct 12 20:48:16 CEST 2007


Dick Moores wrote:
> At 12:34 AM 10/12/2007, Alan Gauld wrote:
>> lstB = lstA[:]   # a full slice creates a copy
>>
>> But thats not an efficient approach if you have a big list, the
>> best route is to build a new list, preferably using a list
>> comprehension.
> 
> Alan, here's a test I made up. It doesn't show your contention is 
> correct, but I imagine you or someone else will show me I don't know 
> what I'm doing. :-)
> 
> Maybe lstA isn't big enough, or complex enough?

If all you want to do is copy the list, then
   lstB = lstA[:]
is fine, or you can use
   lstB = list(lstA)

But the original question was about *filtering* the list. With the copy 
you are back to your original problem - how do I delete items from a 
list while iterating over it? The list comp is probably faster for this 
than anything you can come up with that starts with a copy and then 
deletes items.

Kent

> 
> ===============
> # timing3WaysCopyList.py
> import time
> print "starting at", time.strftime('%H:%M:%S')
> 
> n = 1
> lstA = [1000*'qwerty123456']*10000000
> 
> print "First Way: lstB = lstA[:]"
> print "starting at", time.strftime('%H:%M:%S')
> timeStart = time.time()
> lstB = lstA[:]
> timeEnd = time.time()
> print "Time was %.4g seconds" % (timeEnd - timeStart)
> print
> 
> print "Second Way: for x in lstA"
> print "starting at", time.strftime('%H:%M:%S')
> timeStart = time.time()
> lstC = []
> for x in lstA:
>      lstC.append(x)
> timeEnd = time.time()
> print "Time was %.4g seconds" % (timeEnd - timeStart)
> print
> 
> print "Third Way: List Comprehension"
> print "starting at", time.strftime('%H:%M:%S')
> timeStart = time.time()
> lstD = [x for x in lstA]
> timeEnd = time.time()
> print "Time was %.4g seconds" % (timeEnd - timeStart)
> print
> ======================
> 
> Output:
> 
> First Way: lstB = lstA[:]
> Time was 0.281 seconds
> 
> Second Way: for x in lstA; lstC.append(x)
> Time was 7.359 seconds
> 
> Third Way: List Comprehension [x for x in lstA]
> Time was 4.203 seconds
> =======================
> 
> Dick
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list