Map vs. List Comprehensions (was "lint warnings")

Gerald Britton gerald.britton at gmail.com
Tue Feb 15 18:55:50 EST 2011


Generally, I prefer map() over list comprehensions since they are more
succinct and run faster for non-trivial examples.  However, I've been
considering another use case related to functions in the operator
module.  Here are some examples:

[x.method() for x in data]
[x[0] for x in data]
[x.attr for x in data]

can be implemented as:

from operator import methodcaller, itemgetter, attrgetter

m = methodcaller('method')
g = itemgetter(0)
a = attrgetter('attr')

map(m, data)
map(g, data)
map(a, data)

I find that using map here generally is a little slower than the list
comprehension, perhaps because of the extra work the operator methods
have to do:

>>> m = methodcaller('upper')
>>> g = itemgetter(0)
>>> a = attrgetter('__class__')
>>> s = "a"

>>> Timer('[x.upper() for x in s]', 'from __main__ import s').timeit()
1.8678569793701172
>>> Timer('map(m, s)', 'from __main__ import s, m').timeit()
2.1330718994140625

>>> Timer('[x[0] for x in s]', 'from __main__ import s').timeit()
1.6577358245849609
>>> Timer('map(g, s)', 'from __main__ import s, g').timeit()
1.8645310401916504

>>> Timer('[x.__class__ for x in s]', 'from __main__ import s').timeit()
1.7232599258422852
>>> Timer('map(a, s)', 'from __main__ import s, a').timeit()
2.4131419658660889
>>>

So, what's the feeling out there?  Go with map and the operators or
stick with the list comps?

-- 
Gerald Britton



More information about the Python-list mailing list