Map Filter and Reduce in Python
The functions map(), filter(), and reduce() in Python give the language a hint of functional programming. While List Comprehensions and Loops can be used in place of all three of these convenience functions, in certain situations, they provide a more sophisticated and concise solution.
The operations of map(), filter(), and reduce() are identical. These functions take in a function and a list of elements, and they return the outcome of applying the function that was received to each element in the list.
Map() Method
You can iterate through each item in an iterable using the map() function, just like you can with reduce(). On the other hand, instead of yielding a single result, Map() works independently on each item.
Lastly, you can apply mathematical operations to two or more lists using the map() function. You can even use it to work with an array.
The time complexity of the map() function is O (n).
Syntax:
map(function, iterable)
- function: The function that the code will utilize.
- Iterable: This is the value that the code repeatedly iterates.
Algorithm:
- Make a function called addNumbers that takes a number as input and returns the result of that addition.
- Within the function, return the supplied number added to three.
- Apply the addNumbers() function to each element of the list using the map() function, passing the function name and list as arguments.
- After adding the outcome of items on the list with three, print the results.
Code:
# Creating a function that returns an additional result
def addNumbers(givenNumbers):
# returning number after adding with 3
return (givenNumbers)+3
# map() function applies the addNumbers function
# for each element of the list
givenNumbers = map(addNumbers, [1, 2, 4, 5, 8, 9])
# Printing the resultant list of items
print(":")
For element in givenNumbers:
print(element)
Output:
Adding list elements with 3:
4
5
7
11
12
Filter() Method
A new iterator that filters elements from an existing one (such as a list, tuple, or dictionary) is created by the filter() function.
The filter() function prints the result after determining whether the supplied condition is present in the sequence.
The time complexity of the filter() function is O (n).
Syntax:
filter(function, iterable)
- Function: The function that the code will utilize.
- Iterable: This is the value that the code repeatedly iterates.
Algorithm:
- Make a function called licenseAge that retrieves the list's eligibility ages for voting.
- To determine if the number supplied to the function is greater than or equal to 18, use the if conditional statement.
- Return the number if the claim above is accurate.
- In order to store the input list, create a variable.
- Employ the filter() function to remove entries from the list that are older than or equal to 18 by providing the function name and the input list as arguments. In this case, the licenseAge() function is applied to each element of the list, and the outcome only stores the values returned by the licenseAge() function (in this case, the function returns a number if the value is greater than 18.
- Print the object filter.
- To turn the filter above object into a list and print it, use the list() function, which returns a list of iterates.
Code:
# Creating a function that returns the eligibility ages for voting from the
list
def licenseAge(givenNumumber):
# checking whether the number is greater than or equal to 18
if givenNumumber>=18:
# returning number
return givenNumumber
# input list
inputList = [3, 15, 20, 6, 12, 25, 19]
# Getting only values of the above list that are greater than or equal to 18
result_filterObj = filter(licenseAge, inputList)
# printing the filter object
print(result_filterObj)
# converting into a list
print("Eligibility ages for voting from the input list:", list(result_filterObj))
Output:
By executing the above code, we will get the output as:
<filter object at 0x7fcd3ad14280>
Eligibility ages for voting from the input list: [20, 25, 19]
reduce():
reduce() returns a single value after iterating through each element in a list or other iterable data type in Python. The functools library has it. Looping is less efficient than this.
Syntax:
reduce(function, iterable)
- Function: The function that the code will utilize.
- Iterable: This is the value that the code repeatedly iterates.
Algorithm:
- To import the reduction() function from the functools module, use the import keyword.
- Make a function called multiplyNumbers() that yields the total of all the items in the list.
- Make a variable and use it to hold the input list.
- To obtain the total of all list elements, use the reduce() function using the list as input parameters, avoiding the multiplyNumbers() function.
Code:
# importing reduce() function from functools module
from functools import reduce
# function that returns the product of all list items
def multiplyNumbers(x, y):
return x*y
# input list
inputList = [1, 4, 3, 5, 9, 10]
# Print the sum of the list items using the reduce() function
print("The product of all list items:")
print(reduce(multiplyNumbers, inputList))
Output:
The product of all list items:
540
Upon passing the input list and the addNumbers() function as arguments to the reduce() function, the function will take two list elements and sum them to create a single element. It will then take another list element and sum it once more to create a single element, and so on, until it sums all of the list's elements and returns a single value.