What if you could add hundreds of numbers with just one simple command?
Why sum() function in Python? - Purpose & Use Cases
Imagine you have a long list of numbers, like your monthly expenses, and you want to find out the total amount you spent. Doing this by adding each number one by one manually or writing code to add each element separately can be tiring and slow.
Manually adding numbers or writing a loop to add each item is not only slow but also prone to mistakes. You might forget to add some numbers, or your code might become long and hard to read, especially if the list is very long.
The sum() function in Python quickly adds all numbers in a list or any collection for you. It makes your code shorter, cleaner, and less error-prone by handling the addition automatically.
total = 0 for num in numbers: total += num print(total)
total = sum(numbers) print(total)
With sum(), you can easily and reliably add up many numbers in just one simple step, freeing you to focus on more interesting parts of your program.
For example, if you track your daily steps in a list, sum() helps you quickly find out how many steps you took in a week without writing extra code.
Manually adding numbers is slow and error-prone.
sum() simplifies adding all numbers in a collection.
It makes your code cleaner, shorter, and easier to understand.