Is there a reason to prefer using map()
over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic
I consider that the most Pythonic way is to use a list comprehension instead of map
and filter
. The reason is that list comprehensions are clearer than map
and filter
.
In [1]: odd_cubes = [x ** 3 for x in range(10) if x % 2 == 1] # using a list comprehension
In [2]: odd_cubes_alt = list(map(lambda x: x ** 3, filter(lambda x: x % 2 == 1, range(10)))) # using map and filter
In [3]: odd_cubes == odd_cubes_alt
Out[3]: True
As you an see, a comprehension does not require extra lambda
expressions as map
needs. Furthermore, a comprehension also allows filtering easily, while map
requires filter
to allow filtering.