Using Reduce in Python
Using Reduce in Python
The `reduce` function is part of the `functools` module and is used to apply a function of two
arguments cumulatively to the items of a sequence (like a list) from left to right, so as to reduce the
sequence to a single value.
You need to import `reduce` from the `functools` module because it’s not a built-in function in
Python.
python
The function you pass to `reduce` must take two arguments. This function will be applied
cumulatively to the items of the sequence.
python
You apply `reduce` by passing the function and the sequence you want to reduce. For example,
to sum the numbers in a list:
python
numbers = [1, 2, 3, 4, 5]
result = reduce(add, numbers)
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/3
print(result) # Output: 15
Here’s a more complex example using `reduce` to find the product of all numbers in a list:
python
numbers = [1, 2, 3, 4, 5]
result = reduce(multiply, numbers)
print(result) # Output: 120
You can also use a lambda function with `reduce` for simplicity:
python
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result) # Output: 15
Here, the lambda function `lambda x, y: x + y` performs the same operation as the `add` function
defined earlier.
python
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/3
words = ['Hello', 'World', 'from', 'reduce']
result = reduce(lambda x, y: x + ' ' + y, words)
print(result) # Output: "Hello World from reduce"
In this example, `reduce` will apply the lambda function to concatenate the strings with a space
between them.
Summary
Feel free to ask if you have any specific use case or further questions!
ChatGPT can make mistakes. Check important info.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/3