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

Gerald Britton gerald.britton at
Wed Feb 16 00:55:50 CET 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()
>>> Timer('map(m, s)', 'from __main__ import s, m').timeit()

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

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

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