Tutorial Study Image

Python sum()

The built-in function sum() is used to return the sum of the elements of a given iterable. The sum calculation starts from a specified start point(default 0) and from left to right of iterable.


sum(iterable, start) #where iterable may be list, tuple, dict etc
 

sum() Parameters:

Takes two parameters. If we want to add floating-point numbers with exact precision, in such case we need to use math.fsum(iterable).

Parameter Description Required / Optional
iterable  iterable (list, tuple, dict, etc). The items of the iterable should be numbers Required
start This value is added to the sum of items of the iterable. The default value of start is 0 Optional

sum() Return Value

In the case of iterable with string elements then we need to use join() instead of sum(). The condition of sum() is that the iterable should contain some value, otherwise it will arise an error.

Input Return Value
 Iterable sum of iterable

Examples of sum() method in Python

Example 1: Working of sum()in Python


numberlist = [6, 3.5, -4, 2]

# start parameter is not provided
numberlist_sum = sum(numberlist)
print(numberlist_sum)

# start = 8
numberlist_sum = sum(numberlist, 8)
print(numberlist_sum)
 

Output:

7.5
15.5

Example 2:How to get sum of integers, tuple, dictionary and a list of complex numbers?


listsum=[2,5,7,3,1]
tuple1sum=(40,30,20)
dictsum={ 0:11, 2:22, 5:33, 1:44 }
complx_nums=[ 3+2j, 5+4j, 2+1j]
 
print("list elements sum :",sum(listsum,10))
print("tuple elements sum :", sum(tuplesum))
print("dictionary keys sum :", sum(dictsum))
print("complex numbers sum :", sum(complx_nums))
 

Output:

list elements sum: 28
tuple elements sum: 90
dictionary keys sum: 8
complex numbers sum: (10+7j)