Python sum() Method
The sum()
method returns the total of integer elements starting from left to right of the given iterable.
Syntax:
sum(iterable, start)
Parameters:
- iterable: An iterable such as list, tuple, set, dict with int, float, and complex numbers only.
- start: (optional) This starting value in the calculating sum. Default is 0.
Return Value:
Returns an integer indicating the total of all values of the iterable.
The following example returns the sum of elements of the iterable.
nums = [1, 2, 3, 4, 5]
total = sum(nums)
print("Total = ", total)
total = sum(nums, 5) # start adding 5
print("Total with starting value = ", total)
nums = [10.5, 20.5, 30.5, 4, 5] # with float & int elements
total = sum(nums)
print("Total of mixed elements = ", total)
nums = [3+2j, 5+6j]
total = sum(nums)
print("Total of complex numbers = ", total)
Total = 15
Total with starting value = 20
Total of mixed elements = 70.5
Total of complex numbers = (8+8j)
The sum()
method can also accept set, tuple, dict (only with int keys) to calculate sum of all elements, as shown below.
nums_set = {1, 2, 3, 4, 5}
total = sum(nums_set)
print("Total of set = ", total)
nums_tuple = (1, 2, 3, 4, 5)
total = sum(nums_tuple)
print("Total of tuple = ", total)
nums_dict = {1:'one',2:'two',3:'three'}
total = sum(nums_dict)
print("Total of dict Keys = ", total)
Total of set = 15
Total of tuple = 15
Total of dict keys = 6
Note that passing string or other value will result in TypeError
.