Guido's regrets: filter and map
Robin Becker
robin at jessikat.fsnet.co.uk
Sun Nov 24 06:45:47 EST 2002
In article <pan.2002.11.24.01.35.22.907943 at webone.com.au>, Simon Burton
<simonb at webone.com.au> writes
>Hello,
>
>I just read Guido's "python regret's" slide's from OSCON,
>http://www.google.com/search?hl=en&ie=ISO-8859-1&q=OSCON+%22python+regrets%22
>and one thing i can't work out is,
>he is saying we can do map() and filter() with
>list comprehensions (it's faster too)
>eg.
>
>amapedlist = [ somefunc(x) for x in alist ]
>
>But how would we do a filter with list comprehensions?
>
>
>Simon Burton
all my tests indicate that list comprehensions are not very different
from the equivalent for loop. On the other hand if the function is a
builtin then reduce, map & filter can be much faster.
eg
#######################
from time import time
n = 1000000
N = xrange(n)
t0 = time()
S=[]
a = S.append
for x in N:
a(str(x))
del S
print 'for loop took %.2f' % (time()-t0)
t0 = time()
S = [str(x) for x in N]
del S
print 'list comprehension took %.2f' % (time()-t0)
t0 = time()
S = map(str,N)
del S
print 'map took %.2f' % (time()-t0)
#######################
I repeatedly get
for loop took 5.81
list comprehension took 8.16
map took 4.23
with 2.2.2 win32 on a 1GHz pentium.
What we really need are more useful builtin functions that can be put
into these faster ways of doing things.
--
Robin Becker
More information about the Python-list
mailing list