Google Python style guide
map
and filter
are way less powerful than their list comprehension equivalent. LCs can do both filtering and mapping in one step, they don't require explicit function and can be compiled more efficiently because of their special syntax
# map and filter
map(lambda x:x+1, filter(lambda x:x%3, range(10)))
# same as LC
[x+1 for x in range(10) if x%3]
There is simply no reason to prefer map or filter over LCs.
reduce
is slightly different, because there is no equivalent LC, but it has no big advantage over a ordinary for-loop either.
The Google Python Style guide does not say
prefer list comprehensions and for loops instead of filter, map, and reduce
Rather, the full sentence reads,
Use list comprehensions and for loops instead of filter and map when the function argument would have been an inlined lambda anyway. (my emphasis)
So it is not recommending that you completely avoid using map
, for instance -- only that
[expression(item) for item in iterable]
is preferable to
map(lambda item: expression(item), iterable)
In this case it is clear that the list comprehension is more direct and readable.
On the other hand, there is nothing wrong with using map
like this:
map(str, range(100))
instead of the longer-winded
[str(item) for item in range(100)]
It performs well to boot:
In [211]: %timeit list(map(str,range(100)))
7.81 µs ± 151 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [215]: %timeit [str(item) for item in range(100)]
10.3 µs ± 3.06 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)