Map, Filter, Reduce
Map, Filter, Reduce
Output: [1,32,729]
pow() takes two arguments, x and y, and returns x to the power of y.
In the first iteration, x will be 1, y will be 4, and the result will be 1.
In the second iteration, x will be 2, y will be 5, and the result will be 32,
and so on.
The final iterable is only as long as the shortest iterable, which is first_it
in this case.
Transforming Iterables of Strings With
Python’s map()
• Using the Methods of str
list(map(str.upper, string_it))
['PROCESSING', 'STRINGS', 'WITH', 'MAP']
list(map(str.lower, string_it))
['processing', 'strings', 'with', 'map']
• Using math operations
def powers(x):
return x ** 2, x ** 3
numbers = [1, 2, 3, 4]
list(map(powers, numbers))
• Type conversion
# Convert to floating-point
list(map(float, ["12", "3", "-15"]))
# Convert to integer
list(map(int, ["12.5", "3.0", "-15"]))
Combining map() With Other Functional
Tools
• Sometimes we need to process an input iterable and return another
iterable that results from filtering out unwanted values in the input
iterable.
• In that case, Python’s filter() can be a good option for you.
• filter() is a built-in function that takes two positional arguments:
• function will be a predicate or Boolean-valued function, a function
that returns True or False according to the input data.
• iterable will be any Python iterable.
• filter() yields the items of the input iterable for which function returns
True.
• If you pass None to function, then filter() uses the identity function.
• This means that filter() will check the truth value of each item in
iterable and filter out all of the items that are false.
import math
def is_positive(num):
return num >= 0
def sanitized_sqrt(numbers):
cleaned_iter = map(math.sqrt, filter(is_positive, numbers))
return list(cleaned_iter)