sum of elements in a python list

Sum of Elements in a List in Python

Lists are very commonly used to store sequences of values (for example, numbers) in Python. When working with lists, it can be handy to know how to quickly get the sum of values in a list. For example, you have a list of your recorded footsteps in the last seven days and you want to know the total sum. In this tutorial, we will look at how to get the sum of the elements in a list in Python with the help of some examples.

sum of elements in a python list

You can use the python built-in sum() function to get the sum of list elements. Alternatively, you can use a loop to iterate through the list 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.

The built-in sum() function in Python is used to return the sum of an iterable. To get the sum total of a list of numbers, you can pass the list as an argument to the sum() function.

# create a list
ls = [10, 15, 20, 25]
# sum of list elements
sum(ls)

Output:

70

We get the sum of the values in the list 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 list
ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
# sum of list elements
sum(ls)

Output:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

0.8999999999999999

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 list
ls = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]
# sum of list elements
math.fsum(ls)

Output:

0.9

We get the accurate result this time. For more on the fsum() function, refer to its documentation.

Alternatively, you can use the straightforward method of iterating through the list elements and keeping track of the sum.

# create a list
ls = [10, 15, 20, 25]
# use a loop to get the sum
total = 0
for item in ls:
    total += item
print(total)

Output:

70

We get the sum of the values in the list.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top