May 2019
Beginner
528 pages
29h 51m
English
The preceding section introduced several functional-style features—list comprehensions, filtering and mapping. Here we demonstrate the built-in filter and map functions for filtering and mapping, respectively. We continue discussing reductions in which you process a collection of elements into a single value, such as their count, total, product, average, minimum or maximum.
filter FunctionLet’s use built-in function filter to obtain the odd values in numbers:
In [1]: numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]In [2]: def is_odd(x):...: """Returns True only if x is odd."""...: return x % 2 != 0...:In [3]: list(filter(is_odd, numbers))Out[3]: [3, 7, 1, 9, 5]
Read now
Unlock full access