The reduce() Function
What is r
The
Syntax
To use
Example: Using
Output:
In this example,
Example: Using
Output:
Using
What is r
educe()?The
reduce() function from the functools module applies a function cumulatively to the items of an iterable, reducing the iterable to a single value.Syntax
reduce(function, iterable)
To use
reduce(), you need to import it from the functools module.Example: Using
reduce() to Sum a Listfrom functools import reduce
def add(x, y):
return x + y
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(add, numbers)
print(total_sum)
Output:
15
In this example,
reduce() adds each number in the list to the next, resulting in the sum of all numbers.Example: Using
lambda with reduce()from functools import reduce
numbers = [1, 2, 3, 4, 5]
total_sum = reduce(lambda x, y: x + y, numbers)
print(total_sum)
Output:
15
Using
lambda with reduce() simplifies the function definition.👍3❤1
New users check pinned message 📌
👍6
Are you dead?
👎27👨💻11👍8❤6😁5💯2🗿2🤗1
If you are alive the comment your name👇
👍27❤13🔥3