Python Map, Filter, Reduce
Python Map, Filter, Reduce
This tutorial covers Python Map, Filter, and Reduce.
The three terms refer to programming paradigms of functional approaching.
They provide concise coding efficiency, by allowing function application over multiple iterative data.
Within this page, we cover the following:
- map()
- filter()
- reduce()
Map
The map() method applies a function onto one or more items.
This approach works with Python lists. The outcome is also a list.
The following are three examples of map().
Multiply each item by 3
def multiply(x): return x * 3 someList = [3, 12, 1, 7, 25] mulList = list(map(multiply, someList)) print(mulList) # Output: [9, 36, 3, 21, 75]
We can also use built-in functions (e.g. upper or abs).
Apply uppercase to each item
someList = ["apples", "cars", "winter"] upperList = list(map(str.upper, someList )) print(upperList) # Output: ['APPLES', 'CARS', 'WINTER']
Convert each item to absolute value
someList = [3, -12, 1, -7, -25] absList = list(map(abs, someList)) print(absList) # Output: [3, 12, 1, 7, 25]
Filter
The filter(), as the name suggests, filters through iterative data and passes only datapoints that are True.
This approach outputs a list.
The following are two examples of filter().
Filter items with more than 5 letters
def check_len(x): return len(x) > 5 someList = ["apples", "cars", "winter"] absList = list(filter(check_len, someList)) print(absList) # Output: ['apples', 'winter']
Filter items above 0 (positives only)
def positive(x): return x > 0 someList = [3, -12, 1, -7, -25] absList = list(filter(positive, someList)) print(absList) # Output: [3, 1]
Reduce
The reduce() method applies a function of computation of two arguments to a iterative data.
This approach works with lists and is not built-in into Python. As such, it needs to be imported from the module functools.
The following are two examples of reduce().
Computational sum of two numbers
from functools import reduce def sum(x, y): return x + y someList = [3, 12, 1, 7, 25] compList = reduce(sum, someList) print(compList) # Output: 48
The operations behind the above:
- Take first and second number
- Add them together
- The result becomes the first number
- Add the first (result) and next number
- Repeat until end
someList = [3, 12, 1, 7, 25] 3 + 12 = 15 15 + 1 = 16 16 + 7 = 23 23 + 25 = 48
Computational sum of two numbers (lambda)
Instead of creating a normal function, we can also use lambda.
This creates code neatness.
from functools import reduce someList = [3, 12, 1, 7, 25] compList = reduce(lambda x, y: x + y, someList) print(compList) # Output: 48