Sobes.tech
Junior
196

Tell me about the reduce function in Python.

Answer from AI

sobes.tech AI

The reduce function from the functools module applies a function sequentially to the elements of an iterable. It takes two mandatory arguments: a function with two arguments and an iterable object. Optionally, an initial value can be provided.

Example:

from functools import reduce

# Function to sum two numbers
def add(x, y):
    return x + y

# Summing elements of a list
numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)

# result will be: 1 + 2 = 3, 3 + 3 = 6, 6 + 4 = 10, 10 + 5 = 15

With an initial value:

from functools import reduce

def multiply(x, y):
    return x * y

# Multiplying list elements with an initial value of 10
numbers = [1, 2, 3, 4, 5]
result = reduce(multiply, numbers, 10)

# result will be: 10 (initial) * 1 = 10, 10 * 2 = 20, 20 * 3 = 60, 60 * 4 = 240, 240 * 5 = 1200

The main purpose of reduce is to fold an iterable into a single value.

In modern Python versions, it is often preferable to use list comprehensions, generators, or functions like sum, max, min, all, any for similar results in a more readable way. However, reduce remains a powerful tool for more complex folding operations.