Map, Filter, and Reduce are powerful higher-order functions in Python that can greatly simplify and enhance your code. Let’s explore some examples of their usage.

Table of Contents

  1. Map function
  2. Reduce function
  3. Filter function
  4. Conclusion
Python Functions
Photo by Anna Tarazevich on Pexels.com

Map function

Import the math module to access the sqrt function.

  • Define a function sqrt_numb that takes a number as input and returns the square root of that number using math.sqrt.
  • Create a list called my_list with values [5, 6, 7].
  • Apply the sqrt_numb function to each element in my_list using the map function. Store the result in the output variable.
  • Convert the output variable to a list using the list() function and assign the result to output_list.
  • Print output_list, which will display the square roots of the elements in my_list.
import math
def sqrt_numb(number):
    return math.sqrt(number)

my_list = [5, 6, 7]
output = map(sqrt_numb, my_list)

output_list = list(output)
print(output_list)

Output

[2.23606797749979, 2.449489742783178, 2.6457513110645907]

Reduce function

  • Import the reduce function from the functools module.
  • Create a list called list_numbers with values [2, 4, 6, 8].
  • Use the reduce function to calculate the product of all elements, starting with an initial value of 5. Store the result in the variable. product.
  • Print the data type of product using the type() function, which will output <class 'int'>.
  • Print the value of product, which will display 1920, the product of all the elements in list_numbers.
from functools import reduce
list_numbers = [2, 4, 6, 8]
product = reduce(lambda x, y: x * y,list_numbers,5) #initial value = 5
print(type(product))
print(product)

Output

<class 'int'>
1920

Filter function

  • Define a function called initial_k that takes a dataset as input.
  • Iterate over each element in the dataset.
  • If the first letter of an element, normalized to lowercase, is equal to “k”, return True; otherwise, return False.
  • Create a list called names with values ['Kavitha', 'Kittu', 'Hansa', 'Rakshi', 'Sunitha'].
  • Print names to display the original list.
  • Apply the initial_k function to each element in names using the filter function. Store the result in the names_filtered variable.
  • Print the data type of names_filtered using the type() function, which will output <class 'filter'>.
  • Convert names_filtered to a list using the list() function and assign the result to names_filtered_list.
  • Print the data type of names_filtered_list using the type() function, which will output <class 'list'>.
  • Print names_filtered_list, which will display the filtered list containing only the names that start with the letter ‘K’.
def initial_k(dataset):
    for x in dataset:
        if str.lower(x[0]) == "k": # normalize the case of the
                                   # first letter and look for 'k'
            return True
        else:
            return False

names=['Kavitha','Kittu','Hansa','Rakshi','Sunitha']
print(names)

# extract the True results from the initial_k function to a new filter object
names_filtered = filter(initial_k,names)
print(type(names_filtered))

# convert the filter object to a list object
names_filtered_list = list(names_filtered)
print(type(names_filtered_list))
print(names_filtered_list)

Output

['Kavitha', 'Kittu', 'Hansa', 'Rakshi', 'Sunitha']
<class 'filter'>
<class 'list'>
['Kavitha', 'Kittu']

Conclusion

The examples for map, filter, and reduce boost your skills on the usage in real-life projects.