Get sum of numbers in a list

In this article, we will discuss different ways to get the sum of all numbers in a list in Python.

Table Of Contents

Method 1: Using sum() function

Python provides a function sum(). It accepts a sequence as argument, and returns the sum of all elements in the given sequence. We can pass a list of numbers to it as an argument, and it will return the sum of all numbers in that list. Let’s see an example,

listOfNums = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

# get sum of all numbers in the list
total = sum(listOfNums)

print(total)

Output :

155

We got the sum of all numbers in the list.

Method 2: Using for loop

Iterate over all the numbers in a list, and add them one by one. Let’s see an example,

listOfNums = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

total = 0

# get sum of all numbers in the list
for elem in listOfNums:
    total = total + elem

print(total)

Output :

155

We got the sum of all numbers in the list.

Method 3: Using Generator expression

Iterate over all the numbers in a list using Generator expression. For each element, convert that to int, and pass them to sum() function. It will return the total of all number in the list. Let’s see an example,

listOfNums = ['11', '12', 13, '14', 15, '16', 17, 18, 19, 20]

# get sum of all numbers in the list
total = sum(int(elem) for elem in listOfNums)

print(total)

Output :

155

We got the sum of all numbers in the list.

Summary

We learned how to get the sum of all numbers in a list. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top