Question about order in lists

Mike Fletcher mcfletch at vrtelecom.com
Fri Aug 13 22:33:43 EDT 1999


Understandable behaviour:

l2 = l1[:] -> make a new list with size == l1 with pointers all pointing to
l1's data.

At the C level, this would mean approximately "copy memory range x to new
memory range y" (lists are contiguous arrays of pointers to objects).

Whereas:

for i in xrange(sz):l2.append(i)

Actually goes through x python loop iterations, where it binds the variable
i x times, finds attribute __getitem__ of your xrange x times, calls it x
times, finds the attribute append of l2 x times, and calls that function x
times.  (And every single variable lookup has the potential to fall through
to a higher-level namespace etceteras).  Python's dynamism has a _serious_
impact on performance and algo design ;) .

Oh, and the following is a fairly fast way to create your initial list of
integers (in this case, just a little faster):

range( 1000000 )

Cheers,
Mike

-----Original Message-----
From: python-list-request at cwi.nl [mailto:python-list-request at cwi.nl]On
Behalf Of Darrell
Sent: August 13, 1999 7:06 PM
To: python-list at cwi.nl
Subject: Re: Question about order in lists


You win.
Map is very fast in this case.
Although something intresting happend when I used
l1[:] to create l2
##################
import operator, time

def mapIt(l1, l2):
    map( operator.add, l1,l2)


def loopIt(l1, l2):
    x=[]
    append=x.append
    for i in range(len(l1)):
        append(l1[i]+l2[i])


sz=1000000
l1=[]
for i in xrange(sz):l1.append(i)

if 0:
    # Time1: 5.75 sec
    # Time2: 27.70 sec
    l2=[]
    for i in xrange(sz):l2.append(i)
else:
    # Odd when using these huge numbers
    # This way of creating l2 ran faster ??
    # Time1: 3.25 sec
    # Time2: 28.50 sec
    l2=l1[:]

t1=time.time()
mapIt(l1,l2)
print " Time1: %.2f sec"%(time.time()-t1)
t1=time.time()
loopIt(l1,l2)
print " Time2: %.2f sec"%(time.time()-t1)

####################
# Time1: 3.25 sec
# Time2: 28.50 sec



--Darrell







More information about the Python-list mailing list