Advertisement
Python is filled with simple yet smart tools that make everyday coding smoother. One of them is the sum() function. If you've ever found yourself adding numbers together in a loop, you’ll be glad to know there’s an easier way. sum() quietly handles the heavy lifting, letting you skip all the extra lines of code. Whether you’re working with a list, tuple, or any sequence, sum() makes it fast and easy to get the total.
Let’s break it down and see how this helpful function works.
The sum() function does just what it's named—it adds numbers. You give it a list of numbers (such as a list or tuple), and it gives you their total. No additional fuss, no big steps. Here's the basic format:
python
CopyEdit
sum(iterable, start)
iterable: This is the bulk. It's a list (such as a list or tuple) that holds numbers you wish to add.
start: Optional. It allows you to initialize the starting value of the sum. Python defaults to zero if you don't specify.
Let’s see it in action with a simple example:
python
CopyEdit
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print(total)
Output:
15
Pretty straightforward, right?
Now, if you add a start value, Python will include it in the final sum:
python
CopyEdit
numbers = [1, 2, 3, 4, 5]
total = sum(numbers, 10)
print(total)
Output:
25
Python adds all the numbers together and then adds 10 at the end.
It's tempting to assume sum() only works with simple lists of numbers. But it's much more versatile than that. You can apply it to any iterable: lists, tuples, or even generators.
python
CopyEdit
data = (10, 20, 30)
print(sum(data))
Output:
60
python
CopyEdit
squares = (x * x for x in range(5))
print(sum(squares))
Output:
30
In this case, Python doesn’t create a list in memory. It generates the numbers one by one and adds them up, which saves memory when you're working with big data.
Sometimes, real-life examples help more than just definitions. Let’s see some situations where sum() can make your code cleaner and faster.
Imagine you have a list of test scores, and you want to add only the ones that are passing grades (say, 50 and above).
You can do this:
python
CopyEdit
scores = [45, 67, 89, 32, 90, 50]
passing_scores = [score for score in scores if score >= 50]
total_passing = sum(passing_scores)
print(total_passing)
Output:
296
Quick and clear. No need for long loops.
Let’s say you have a dictionary where keys are product names and values are prices. You want to find the total price of everything.
python
CopyEdit
products = {
'book': 12.99,
'pen': 1.99,
'notebook': 5.49
}
total_price = sum(products.values())
print(total_price)
Output:
20.47
Here, products.values() gives all the prices, and sum() takes care of the rest.
If you want to sum only certain items based on a condition, a generator expression works perfectly.
For example, summing even numbers:
python
CopyEdit
numbers = [1, 2, 3, 4, 5, 6]
total_evens = sum(x for x in numbers if x % 2 == 0)
print(total_evens)
Output:
12
No need to first build a list of evens—Python filters and sums them in one smooth move.
While sum() is simple, there are a few small things that can trip you up if you’re not paying attention.
sum() expects numbers. If your list has anything that’s not a number, you’ll get an error.
For example:
python
CopyEdit
items = [1, 2, '3', 4]
print(sum(items))
Python throws:
bash
CopyEdit
TypeError: unsupported operand type(s) for +: 'int' and 'str'
So, always make sure your iterable has the right data types.
Unlike JavaScript or other languages where adding strings together is common, Python doesn’t let you use sum() for strings. If you try, you’ll see this:
bash
CopyEdit
TypeError: sum() can't sum strings [use ''.join(seq) instead]
If you need to combine strings, ''.join() is your friend, not sum().
Even though sum() works nicely with lists and tuples of numbers, it doesn’t play well with non-numeric sets. For instance, if you have a set of strings and you try to add them using sum(), Python will raise an error. This happens because sum() is designed for numeric addition, not for combining different types of objects.
Example of what not to do:
python
CopyEdit
words = {'hello', 'world'}
print(sum(words))
Python throws:
bash
CopyEdit
TypeError: unsupported operand type(s) for +: 'int' and 'str'
If you're working with sets of text, you'll need to use methods like join() instead. Stick with numbers for sum(), and you’ll stay out of trouble.
If you are adding up huge lists of floating-point numbers, small rounding errors can sneak in because of how computers handle decimals. It’s not a problem for most everyday tasks, but if you're doing sensitive scientific work, you might need something like math.fsum() for better precision.
Here’s how math.fsum() works:
python
CopyEdit
import math
numbers = [0.1] * 10
print(sum(numbers)) # 0.9999999999999999
print(math.fsum(numbers)) # 1.0
You can see the difference.
sum() in Python is one of those quiet tools that saves time without making a fuss. It’s quick, clean, and easy to use when working with numbers in any iterable. Whether you’re totaling up a list of scores, calculating costs, or just making code look cleaner, sum() is ready to help. Just keep an eye out for non-numeric data, and if you need perfect accuracy with floating-point numbers, remember that math.fsum() has your back. Now that you know how to use sum(), you’ll probably find yourself reaching for it more often without even thinking about it. Happy coding!
Advertisement
Apple unveiled major AI features at WWDC 24, from smarter Siri and Apple Intelligence to Genmoji and ChatGPT integration. Here's every AI update coming to your Apple devices
Explore how labeled data helps machines learn, recognize patterns, and make smarter decisions — from spotting cats in photos to detecting fraud. A beginner-friendly guide to the role of labels in machine learning
Looking for a laptop that works smarter, not harder? See how Copilot+ PCs combine AI and powerful hardware to make daily tasks faster, easier, and less stressful
Want to learn how machine learning models are built, deployed, and maintained the right way? These 8 free Google courses on MLOps go beyond theory and show you what it takes to work with real systems
Wondering how everything from friendships to cities are connected? Learn how network analysis reveals hidden patterns and makes complex systems easier to understand
Tired of missed calls and endless voicemails? Learn how Synthflow AI automates business calls with real, human-like conversations that keep customers happy and boost efficiency
Learn what stored procedures are in SQL, why they matter, and how to create one with easy examples. Save time, boost security, and simplify database tasks with stored procedures
Understand the principles of Greedy Best-First Search (GBFS), see a clean Python implementation, and learn when this fast but risky algorithm is the right choice for your project
Learn how to build an AI app that interacts with massive SQL databases. Discover essential steps, from picking tools to training the AI, to improve your app's speed and accuracy
From training smarter AI to protecting privacy, synthetic data is fueling breakthroughs across industries. Find out what it is, why it matters, and where it's making the biggest impact right now
Wondering if there’s an easier way to add up numbers in Python? Learn how the sum() function makes coding faster, cleaner, and smarter
The Dead Internet Theory claims much of the internet is now run by bots, not people. Find out what this theory says, how it works, and why it matters in today’s online world