Free Python Course | Programming Tutorials
599 subscribers
9 photos
2 files
6 links
Join Noob to Pro in Python in 100 Days! 🚀 Learn Python with daily lessons, practical examples, free code samples, exercises, and homework. Ideal for beginners and those looking to advance their skills. Start your journey to becoming a Python pro! 🐍
Download Telegram
The reduce() Function

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 List
from 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.
👍31
New users check pinned message 📌
👍6
Creating 100 days perfect plan that's why didn't post anything today🙂
6👍5🔥1
pythoncourse.pdf
433.5 KB
🔥41
Are you dead?
👎27👨‍💻11👍86😁5💯2🗿2🤗1
If you are alive the comment your name👇
👍2713🔥3