# map and filter

### map¶

Maps one iterable onto another.

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

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

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

These would be neater using list comprehensions.

In :
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 :
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 :
result = filter(lambda x: x % 2, range(13))
list(result)

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

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

### Combining map and filter¶

You can map items and then filter the result.

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

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