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)

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



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

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))


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