Table of content

## How to calculate the sum of numbers in a list in python?

The sum of a list is the addition of all the numbers present in the list. For example, consider a list [1, 5, 7]. The sum of the list is 13.

### Calculating sum using the sum() function

Python provides an inbuilt function sum() which sums up the numbers in the list. The example using the sum() function is shown below.

``````num = [5, 6, 3, 4, 8]
print("List of numbers", num)
add = sum(num)
print("Addition of all the numbers in a list is", add)``````

Output

``````List of numbers [5, 6, 3, 4, 8]
Addition of all the numbers in a list is 26``````

### Calculating the sum using for loop

Given a list of numbers num a for loop can be used to iterate over each and every element and it to the variable add. The variable add is initialized to '0' initially.

``````num = [5, 6, 3, 4, 8]
print("List of numbers", num)
add = 0
for i in num:
add += i
print("Addition of all the numbers in a list is", add)``````

Output

``````List of numbers [5, 6, 3, 4, 8]
Addition of all the numbers in a list is 26``````
If the elements present in the list are other than the number then, the code raises a TypeError exception. Hence, all the elements present in a list must be a number.

Example,

``````num = [5, 6, 3, 4, "Hello"]
print("List of numbers", num)
add = sum(num)
print("Addition of all the numbers in a list is", add)
``````

Output

``````add = sum(num)
TypeError: unsupported operand type(s) for +: 'int' and 'str'``````
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions