[Tutor] 2 problems in a small script

Dick Moores rdm at rcblue.com
Fri Oct 12 16:22:36 CEST 2007


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?

===============
# 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




More information about the Tutor mailing list