The map, filter, and reduce functions

Other functions that you might find useful with data structures are map, filter, and reduce. These are very useful in conjunction with other functions, such as lambdas.

map runs given functions on every element of the iterable, returning a generator:

>>> data1, data2 = (1, 2, 3, 4, 5), ('A', 'B', 'C', 'D', 'E')

>>> list(map(lambda x: x**2, data1))
# converting to list in order to seE results
[1, 4, 9, 16, 25]

>>> list(map(lambda x: x.lower(), data2))
['a', 'b', 'c', 'd', 'e']

Similarly, filter returns a subarray of elements for which the function returns a true or truthy value:

list(filter(lambda x: x > 3, data1))
>>> [4, 5]

Finally, reduce—which was moved to the itertools package in Python 3—runs given functions on pairs and in cascades, with the expectation to get one value as a result so that all the values will triple down to one. For example, the sum function can be seen as a specific case of reduce.

While it is useful to know that those functions exist, there is another more expressive method that can achieve the same results—comprehensions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset