map and filter

map

Maps one iterable onto another.

result = map(lambda x: x**2, range(7))
list(result)
[0, 1, 4, 9, 16, 25, 36]
a = range(7)
b = range(3, 10)
result = map(lambda x, y: y**2-x, a, b)
list(result)
[9, 15, 23, 33, 45, 59, 75]

These would be neater using list comprehensions.

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.

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.

result = filter(lambda x: x % 2, range(13))
list(result)
[1, 3, 5, 7, 9, 11]
result = filter(lambda x: x > 3, range(13))
list(result)
[4, 5, 6, 7, 8, 9, 10, 11, 12]

Combining map and filter

You can map items and then filter the result.

result = filter(lambda x: x % 2, map(lambda x: x-11, range(21)))
list(result)
[-11, -9, -7, -5, -3, -1, 1, 3, 5, 7, 9]

If you spot any errors please let me know on twitter.