Python provides the sum()
method which is used to sums the provided iterable which can be a list, a set or etc. The sum operation is executed from left to right and the total value is returned as the return value.
sum() Method Syntax
The sum() method has the following syntax where the second parameter is optional.
sum(ITERABLE,START)
- ITERABLE is an interable object like list, set etc.
- START parameter is optional and if specified and added to the sum of ITERABLE.
Sum List Items
The sum() method is generally used to sum specified list items. The list items should be numbers like integers, floating points, etc. In the following examples, we use the list named “numbers” which contains integers for the first example. In the second example, the list numbers contain integer and floating-point values.
numbers = [1,2,3]
result = sum(numbers)
print(result)
numbers = [1,2,3,4.5]
result = sum(numbers)
print(result)
6 10.5
Sum List Items with Start Value
We can also provide the start value in order to start sum operation from left to right. In the following example, we start the sum operation with value 2.
numbers = [1,2,3]
result = sum(numbers,2)
print(result)
numbers = [1,2,3,4.5]
result = sum(numbers,2)
print(result)
8 12.5
Unsupported Operand Type Error
The sum() method can be used with the list which only contains numbers like integers and floating-point numbers. If the list contains other types like string etc. the sum() operation returns an exception like “Unsupported Operand Type Error“.
