Python has many features of functional programming. Two of the most handy operations are filter and map.
Filter
Filter lets us apply a boolean function to a list and return a list where each item meets the condition of the boolean function.
In general, if f is a boolean function, and lst is a list, we can write:
filter(f, lst)
We do not have to use named functions; we can use lambda functions instead.
The following applies the boolean function with condition x > 5 to a list.
lst = [2, 4, 6, 8, 10] result = filter(lambda x: x > 5, lst) print(list(result))
Result:
[6, 8, 10]
Note the use of list() to convert to a list, since the result of filter is a map object.
Map
Map lets us apply any function to all items in a list, resulting in a list where each item becomes the return value of the function application to that item.
In general:
map(f, lst)
The following example shows how to map a squaring function to each element in the list.
lst = [1, 2, 3, 4] result = map(lambda x: x**2, lst) print(list(result))
Result:
[1, 4, 9, 16]
Note that map returns a map object so we must convert this to a list.
To get a simple list, we need to call list() on the map object.
Without the conversion to a list, printing the result itself would give:
<map object at 0x10082c4f0>
Therefore, we usually need to use list() on the results of map and filter applications.
