FUNCTIONAL PROGRAMMING IN PYTHON: THE FILTER() FUNCTION
This section illustrates how to use the filter() function and also how to combine the filter() and map() functions in Python.
Listing 3.22 displays the contents of filter1.py that illustrates how to use the Python filter() function.
Listing 3.22: filter1.py
numbers = [-10, 11, -20, 55, 100, 201]
even_vals = list(filter(lambda x: x % 2 == 0, numbers))
print("numbers:",numbers)
print("even:   ",even_vals)
Listing 3.22 initializes the variable numbers with a list of integers and then initializes the variable even_vals as a list of values that is returned by the filter() function that uses a lambda expression to return only even integers from the integers in the variable numbers. The output from Listing 3.22 is as follows:
numbers: [-10, 11, -20, 55, 100, 201]
even:    [-10, -20, 100]
Combining the filter() and map() Functions
Listing 3.23 displays the contents of filter_map1...