Always use list comprehensions

List comprehension are clearer than the map and filter built-in functions because they don't require lambda expressions.

list comprehension also allows you skip items from the input list (similar to filter), a behavior that map doesn't support this without the help from filter.

Use list comprehension rather than map and filter

Lets say, I want to compute square of each number.

for loop style:

a = [1,2,3,4,5,6,7,8,9]
squares = []
for i in a:
	squares.append(x ** 2)
print(squares)

map style (note: unable to filter)

squares = map(lambda x: x ** 2, a)
print(squares)

list comprehension style

squares = [x**2 for i in a]
print(square)

the following example show how to combine map and filter using list comprehensions

a = [0,1,2,3,4,5]
b = [x **2 for x in a if x != 0]
print(b)

How about the performance

In most case, map is faster than list comprehension.[1]

$ python -m timeit -s'xs=range(10)' 'map(hex, xs)'
5000000 loops, best of 5: 69.8 nsec per loop
$ python -m timeit -s'xs=range(10)' '[hex(x) for x in xs]'
500000 loops, best of 5: 411 nsec per loop

  1. https://stackoverflow.com/questions/1247486/list-comprehension-vs-map ↩︎