Python map(), filter(), reduce(): A Comprehensive Guide
Introduction to Python map(), filter(), and reduce() Functions
Python's map(), filter(), and reduce() are powerful functional programming constructs that allow us to apply a function to a sequence, filter elements from a sequence, or reduce a sequence to a single value. This tutorial will explore each of these functions through examples and detailed explanations.
Python map() function - The map() function is used to execute a specified function for each item in a iterable.
Python filter() function - The filter() function construct an iterator from those elements of iterable for which function returns true.
Python reduce() function - Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.
Example 1: Using map() to Apply a Function to a List
This example demonstrates using map() to apply a lambda function that squares each number in a list, returning a new list of squared values.
Code:
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# Using map() to square each number in the list
squared_numbers = list(map(lambda x: x ** 2, numbers))
# Output: [1, 4, 9, 16, 25]
print(squared_numbers)
Explanation:
- 'map()' Function: 'map()' takes two arguments: a function and an iterable (like a list). It applies the function to each element in the iterable.
- Lambda Function: The lambda function ‘lambda x: x ** 2’ squares each number.
- Result: 'map()' returns a map object, which we convert to a list to get the squared numbers.
Example 2: Using map() with a Built-In Function
This example shows how to use 'map()' with a built-in function ('int') to convert a list of strings into a list of integers.
Code:
# A list of strings representing numbers
str_numbers = ['1', '2', '3', '4', '5']
# Using map() to convert each string to an integer
int_numbers = list(map(int, str_numbers))
# Output: [1, 2, 3, 4, 5]
print(int_numbers)
Explanation:
- 'map()' Function: Applies the 'int' function to each element in the 'str_numbers' list.
- Result: Converts a list of strings into a list of integers.
Example 3: Using filter() to Filter Even Numbers
This example uses filter() with a lambda function to extract only even numbers from a list, resulting in a new list of even numbers.
Code:
# A list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Using filter() to keep only even numbers
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
# Output: [2, 4, 6, 8, 10]
print(even_numbers)
Explanation:
- 'filter()' Function: 'filter()' takes a function and an iterable and returns a new iterable with elements that return 'True' for the function.
- Lambda Function: The lambda function lambda 'x: x % 2 == 0' checks if a number is even.
- Result: Returns a list containing only the even numbers from the original list.
Example 4: Using filter() to Remove Empty Strings
This example demonstrates using filter() to remove empty strings and strings containing only spaces from a list, leaving only non-empty words.
Code:
# A list of strings
words = ["apple", "", "banana", " ", "cherry", ""]
# Using filter() to remove empty strings and strings with only spaces
non_empty_words = list(filter(lambda x: x.strip(), words))
# Output: ['apple', 'banana', 'cherry']
print(non_empty_words)
Explanation:
- 'filter()' Function: Removes elements that are empty or contain only spaces.
- Lambda Function: 'lambda x: x.strip()' removes leading and trailing spaces, and the 'filter()' function filters out empty results.
- Result: Returns a list with only non-empty strings.
Example 5: Using reduce() to Sum a List of Numbers
This example shows how to use 'reduce()' to sum all the elements in a list, demonstrating the reduction of a list to a single cumulative value.
Code:
from functools import reduce
# A list of numbers
numbers = [1, 2, 3, 4, 5]
# Using reduce() to sum the numbers in the list
total_sum = reduce(lambda x, y: x + y, numbers)
# Output: 15
print(total_sum)
Explanation:
- 'reduce()' Function: 'reduce()' takes a function and an iterable and applies the function cumulatively to the items, reducing the iterable to a single value.
- Lambda Function: 'lambda x, y: x + y' adds two numbers together.
- Result: Returns the sum of all numbers in the list.
Example 6: Using ‘reduce()’ to Find the Maximum Value
Code:
from functools import reduce
# A list of numbers
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
# Using reduce() to find the maximum value in the list
max_value = reduce(lambda x, y: x if x > y else y, numbers)
# Output: 9
print(max_value)
Explanation:
- 'reduce()' Function: Finds the maximum value by comparing each pair of numbers.
- Lambda Function: 'lambda x, y: x if x > y' else y returns the greater of two numbers.
- Result: Returns the maximum value in the list.
Example 7: Combining 'map()', 'filter()', and 'reduce()'
This example combines 'map()', 'filter()', and 'reduce()' to perform a series of transformations on a list, resulting in the sum of even squares.
Code:
from functools import reduce
# A list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# Using map() to square the numbers, filter() to keep even squares, and reduce() to sum them
result = reduce(lambda x, y: x + y,
filter(lambda x: x % 2 == 0,
map(lambda x: x ** 2, numbers)))
# Output: 364 (4 + 16 + 36 + 64 + 100 + 144)
print(result)
Explanation:
- 'map()': Squares each number in the list.
- 'filter()': Keeps only the even squares.
- 'reduce()': Sums the even squares.
- Result: Combines all three functions to produce the sum of the even squares.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python/functional-programming-map-filter-reduce.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics