sum() function in Python (original) (raw)

Last Updated : 02 Jan, 2025

The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list.

Python `

arr = [1, 5, 2] print(sum(arr))

`

Sum() Function in Python Syntax

Syntax : sum(iterable, start)

Possible two more syntaxes

sum(a) : a is the list , it adds up all the numbers in the list a and takes start to be 0, so returning only the sum of the numbers in the list.
sum(a, start) : this returns the sum of the list + start The sum

Python Sum() Function Examples

Get the sum of the list in Python .

Python `

numbers = [1,2,3,4,5,1,4,5]

Sum = sum(numbers) print(Sum)

Sum = sum(numbers, 10) print(Sum)

`

Here below we cover some examples using the sum function with different datatypes in Python to calculate the sum of the data in the given input

Python Sum Function on a Dictionary

In this example, we are creating a tuple of 5 numbers and using sum() on the dictionary in Python.

Python `

my_dict = {'a': 10, 'b': 20, 'c': 30} total = sum(my_dict.values()) print(total)

`

Python Sum Function on a Set

In this example, we are creating a tuple of 5 numbers and using sum() on the set in Python.

Python `

my_set = {1, 2, 3, 4, 5} total = sum(my_set) print(total)

`

Python Sum Function on a Tuple

In this example, we are creating a tuple of 5 numbers and using sum() on the tuple in Python.

Python `

my_tuple = (1, 2, 3, 4, 5) total = sum(my_tuple) print(total)

`

The sum in Python with For Loop

In this, the code first defines a list of numbers. It then initializes a variable called total to 0. The code then iterates through the list using a for loop, and for each number in the list, it adds that number to the total variable. Finally, the code prints the total value, which is the sum of the numbers in the list.

Python `

Define a list of numbers

numbers = [10, 20, 30, 40, 50]

Initialize a variable to store the sum

total = 0

Iterate through the list and add each number to the total

for num in numbers: total += num

Print the sum of the numbers

print("The sum of the numbers is:", total)

`

Output

The sum of the numbers is: 150

Error and Exceptions

TypeError : This error is raised when there is anything other than numbers in the list . In the given example we are using a list of strings rather than an integer.

Python `

arr = ["a"]

start parameter is not provided

Sum = sum(arr) print(Sum)

start = 10

Sum = sum(arr, 10) print(Sum)

`

Output :

Traceback (most recent call last):
File "/home/23f0f6c9e022aa96d6c560a7eb4cf387.py", line 6, in
Sum = sum(arr)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Practical Application

Problems where we require the sum to be calculated to do further operations such as finding out the average of numbers.

Python `

numbers = [1,2,3,4,5,1,4,5]

start = 10

Sum = sum(numbers) average= Sum/len(numbers) print (average)

`