#Use the sum function
print(sum([1, 2, 3]))
The sum()
function is used to get the sum of the items in a given iterable such as list, tuples, sets e.tc. It takes one required positional argument i.e the iterable , and an optional argument, start
, which specifies the initial value, or the start value, for the sum.
Syntax:
sum(iterable, start = 0)
start
defaults to 0 if not provided. If the iterable contains no items, it returns start.
The function iterates through the given iterable, and adds the value of each item to the total sum.
Example:
sum([])
//0
sum([1, 2, 3, 4])
//10
sum((10, 20, 30, 40))
//100
sum([], 10)
//10
sum({10, 20, 30, 40}, 100)
//200
sum((0.5, 0.7, 0.3), 1.5)
//3.0
The function only works when the iterable
contains numerical data i.e integers, floats and complex.
sum(['hello', 'world!'])
//TypeError: unsupported operand type(s) for +: 'int' and 'str'
sum(['hello', 'world!'], '')
//TypeError: sum() can't sum strings [use ''.join(seq) instead]