map and filter

map¶

Maps one iterable onto another.

In [26]:
result = map(lambda x: x**2, range(7))
list(result)

Out[26]:
[0, 1, 4, 9, 16, 25, 36]
In [27]:
a = range(7)
b = range(3, 10)
result = map(lambda x, y: y**2-x, a, b)
list(result)

Out[27]:
[9, 15, 23, 33, 45, 59, 75]

These would be neater using list comprehensions.

In [33]:
print([x**2 for x in range(7)])
print([y**2-x for x, y in zip(range(7), range(3, 10))])

[0, 1, 4, 9, 16, 25, 36]
[9, 15, 23, 33, 45, 59, 75]


Or as generator expressions.

In [29]:
result_1 = (x**2 for x in range(7))
result_2 = (y**2-x for x, y in zip(range(7), range(3, 10)))
print(list(result_1))
print(list(result_2))

[0, 1, 4, 9, 16, 25, 36]
[9, 15, 23, 33, 45, 59, 75]


Thus map is a pretty redundant function.

filter¶

Returns items for which the function evaluates True.

In [30]:
result = filter(lambda x: x % 2, range(13))
list(result)

Out[30]:
[1, 3, 5, 7, 9, 11]
In [31]:
result = filter(lambda x: x > 3, range(13))
list(result)

Out[31]:
[4, 5, 6, 7, 8, 9, 10, 11, 12]

Combining map and filter¶

You can map items and then filter the result.

In [32]:
result = filter(lambda x: x % 2, map(lambda x: x-11, range(21)))
list(result)

Out[32]:
[-11, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9]