89DEVs

Python sum() function

overview

The sum() function returns the sum of all elements of an iterable. The sum() function can be used on iterables like lists, tuples and dictionaries.

sum() on list

The sum() function applied on a list, adds all the elements and returns the sum of all elements. # sum() function lists numbers = [1, 2, 3, 4, 5] mySum = sum(numbers) print(mySum) The sum of all elements in the numbers list is 15. 15

syntax of sum()

The syntax of the sum() function is: sum(iterable[, start=0])

arguments of sum()

The sum() functions accepts one or two arguments. The first argument is required and it is the iterable to calculate to sum off. The second argument is optional and can be passed to increment the sum by the given value. The first argument has to be an iterable, otherwise an TypeError exception is raised. TypeError: 'int' object is not iterable

return value of sum()

The sum() function returns the sum of all elements of the given iterable.

                
        

Summary


Click to jump to section