The Python reduce()
function is used to apply a given function to a sequence of elements from left to right and reduces it to a single value. This type of operation is commonly referred to as a “reduction” or “fold”. Remember, the reduce()
function in Python is not a built-in function, but rather a part of the functools
module. In this article, I will provide a comprehensive overview of the reduce()
function, including its various use cases with examples.
1. Quick Examples of Python reduce() Function
Below is a list of quick examples that can give you a high level understanding of reduce()
function. We will see more details in next sections.
# Quick examples
# Import
from functools import reduce
# Find the product of all elements in a list
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print("Product:", product)
# Find the sum of all elements in a list
numbers = [1, 2, 3, 4, 5]
sum = reduce(lambda x, y: x + y, numbers)
print("Sum:", sum)
# Find the longest word in a list
words = ['Python', 'Spark']
longest_word = reduce(lambda x, y: x if len(x) > len(y) else y, words)
print("Longest word:", longest_word)
# Find the union of of sets
sets = [{1, 2, 3}, {2, 3, 4}]
union = reduce(lambda x, y: x | y, sets)
print("Union:", union)
2. Syntax of Python reduce() Function
The reduce()
function is a part of the functools module, so you need to import the functools
module. Below is the syntax of the reduce()
function.
# Syntax of reduce()
functools.reduce(function, iterable, initializer=None)
2.1 Parameters of the reduce() Function
The reduce()
function, takes 3 parameters. Two of the parameters are required while one is the optional parameter.
function
: The function that is to be applied to the elements of the iterable. This function should take two arguments.iterable
: It can be a list, tuple, or any other iterable data type.initializer
: An optional argument, which is the initial value for the accumulator. If not provided, the first item of the iterable is used as the initializer.
2.2 Return Value of reduce() Function
The reduce()
function returns a single reduced value that is the result of cumulatively applying the function to the elements of the iterable. The reduced value is the final result of the function and is returned to the caller.
2.3 Example of reduce() Function
In the following example, the reduce()
function is applied to mylist
with a lambda function, that takes two arguments x
and y
and returns their product. The reduce()
function cumulatively applies this function to the elements of mylist
and returns a single reduced value, which is the product of all elements in the list.
from functools import reduce
mylist = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, mylist)
print(product)
# Output:
# 120
3. reduce() with Built-in Functions
The reduce()
function can be used with built-in functions in Python to perform a specific operation on a list of elements. The built-in functions used with reduce()
can be any function that takes two arguments and returns a single value.
See the following example:
# The max() function takes two parameters
maximum = reduce(lambda x, y: max(x, y), mylist)
print(maximum)
# Output:
# 5
4. reduce() with a Lambda Function
Using the reduce()
function with a lambda
function is the most common case of use in Python. A lambda function is a small anonymous function that takes one or more arguments and returns a single value.
The simplicity and versatility of lambda functions make them well-suited for use with the reduce()
function to perform operations on a list of elements.
# Use the reduce function with a lambda function
sum_of_squares = reduce(lambda x, y: x + y**2, mylist)
# Print the result
print(sum_of_squares)
# Output:
# 55
5. reduce() with a Custom Function
Instead of using a lambda
function, you can create your own custom function that defines the operation to be performed on the elements. Using the reduce()
with a custom function is a way to apply a specific operation to the elements of a list and return a single reduced value as the result.
# Define a custom function to calculate the sum of squares
def square_sum(x, y):
return x + y**2
# Use the reduce function with the custom function
result = reduce(square_sum, mylist)
print(result)
# Output:
# 55
6. Using reduce() with Sets
It’s important to note that the reduce()
function can be used with any iterable object, not just lists. As you know set is an iterable, so the reduce()
function can also be used with sets in Python. A set is an unordered collection of unique elements.
See the following example:
myset = {1, 2, 3, 4, 5}
product = reduce(lambda x, y: x * y, myset)
print(product)
# Output :
# 55
7. Using reduce() with Dictionaries
When using the reduce()
function with a dictionary, the function is applied cumulatively to the values of the dictionary. This means that the function takes the first two values from the dictionary, applies the function to these two values. And then takes the result and applies the function to the next value in the dictionary.
mydict = {'spark': 3, 'python': 2}
product = reduce(lambda x, y: x * y, mydict.values())
print(product)
# Output:
# 6
In the above example, reduce()
function is applied to the values of mydict
using a lambda
function that calculates the product of x
and y
.
Summary and Conclusion
In this article, you have learned what is reduce() function in Python, and how to use it with built-in functions, lambda functions, custom functions, sets, and dictionaries. I hope this tutorial has provided a clear understanding of how to use the reduce()
function. If you still have any questions, feel free to ask in the comments section.
Keep learning and happy coding!