When working with tuples, it can be handy to know how to quickly get the sum of values in a tuple. For example, you have a tuple containing taxes paid by you in the last five years and you want to calculate the total tax paid. In this tutorial, we will look at how to get the sum of the elements in a tuple in Python with the help of some examples.
Tuples, similar to lists, are data structures used to store an ordered collection of objects in Python. But unlike lists which are very flexible, objects in a tuple cannot be altered.
How to get the sum of a tuple of numbers in Python?
You can use the python built-in
sum() function to get the sum of tuple elements. Alternatively, you can use a loop to iterate through the items and use a variable to keep track of the sum.
Let’s look at the above-mentioned methods with the help of some examples.
sum() to get the total in a tuple
sum() function in Python is used to return the sum of an iterable. To get the sum total of a tuple of numbers, you can pass the tuple as an argument to the
# create a tuple t = (1, 2, 3, 4) # sum of tuple elements print(sum(t))
We get the sum of the values in the tuple as a scaler value.
Note that the
sum() function may result in loss of precision with extended sums of floating-point numbers. For example –
# create a tuple t = (0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1) # sum of tuple elements print(sum(t))
As an alternative, you can use the
math standard library’s
fsum() function to get an accurate sum of floating-point numbers and prevent loss of precision.
import math # create a tuple t = (0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1) # sum of tuple elements print(math.fsum(t))
We get the accurate result this time. For more on the
fsum() function, refer to its documentation.
Using loop to get the sum
Alternatively, you can use the straightforward method of iterating through the tuple elements and keeping track of the sum.
# create a tuple t = (1, 2, 3, 4) # use a loop to get the sum total = 0 for item in t: total += item print(total)
We get the sum of the values in the tuple.
You might also be interested in –
- Get Average of Elements in a Python Tuple
- Get Median of a Tuple in Python
- Sum of Elements in a List in Python
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.