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

G

Gerald Britton

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?
 
S

Steven D'Aprano

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

Stick to whatever feels and reads better at the time.

Unless you have profiled your code, and determined that the map or list
comp was the bottleneck, who cares if you save half a nanosecond per
iteration?

map clearly loses badly in the old-time idiom:

map(lambda x: x+1, seq)

or similar. That's the only time I'd just flat out say, avoid map in
favour of a list comprehension. Otherwise, the performance difference is
likely to be trivial, as is the difference in length of code. Use
whichever you like.

I personally appreciate the ability to treat map as a primitive ("map
this function over this data") rather than caring about the mechanics of
iteration ("iterate over data, applying this function to each element in
turn"), so I often use map. But I use list comps even more often.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,071
Latest member
MetabolicSolutionsKeto

Latest Threads

Top