# Python — Using reduce()

Importing reduce
To use reduce(), you need to import it from the functools module:

from functools import reduce
Example 1: Sum of Elements
Let's start with a simple example: calculating the sum of all elements in a list.

numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result)

#clcoding.com
15
Example 2: Product of Elements
Similarly, you can calculate the product of all elements in a list.

numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result)

#clcoding.com
120
Example 3: Finding the Maximum Element
You can use reduce() to find the maximum element in a list.

numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x if x > y else y, numbers)
print(result)

#clcoding.com
5
Example 4: Concatenating Strings
You can use reduce() to concatenate a list of strings into a single string.

words = ["Hello", "World", "from", "Python"]
result = reduce(lambda x, y: x + " " + y, words)
print(result)

#clcoding.com
Hello World from Python
Example 5: Using an Initial Value
You can provide an initial value to reduce(). This initial value is placed before the items of the sequence in the calculation and serves as a default when the sequence is empty.

numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers, 10)
print(result)

#clcoding.com
25
Example 6: Flattening a List of Lists
You can use reduce() to flatten a list of lists into a single list.

lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
result = reduce(lambda x, y: x + y, lists)
print(result)

#clcoding.com
[1, 2, 3, 4, 5, 6, 7, 8]
Example 7: Finding the Greatest Common Divisor (GCD)
You can use reduce() with the gcd function from the math module to find the GCD of a list of numbers.

import math

numbers = [48, 64, 256]
result = reduce(math.gcd, numbers)
print(result)
16
Example 8: Combining Dictionaries
You can use reduce() to combine a list of dictionaries into a single dictionary.

dicts = [{'a': 1}, {'b': 2}, {'c': 3}]
result = reduce(lambda x, y: {**x, **y}, dicts)
print(result)

#clcoding.com
{'a': 1, 'b': 2, 'c': 3}
Example 9: Custom Function with reduce()
You can also use a custom function with reduce(). Here's an example that calculates the sum of squares of elements in a list.

def sum_of_squares(x, y):
return x + y**2

numbers = [1, 2, 3, 4]
result = reduce(sum_of_squares, numbers, 0)
print(result)

#clcoding.com
30