ExampleEdit & Run
#Use the sum function

print(sum([1, 2, 3]))
copy
Output:
6 [Finished in 0.0106067955493927s]

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

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.

ExampleEdit & Run
print( sum([]) )

print( sum([1, 2, 3, 4]) )

print( sum((10, 20, 30, 40)) )

print( sum([], 10) )

print( sum({10, 20, 30, 40}, 100) )

print( sum((0.5, 0.7, 0.3), 1.5) )
copy
Output:
0 10 100 10 200 3.0 [Finished in 0.010238892398774624s]

The function only works when the iterable contains numerical data i.e integers, floats and complex.

ExampleEdit & Run
sum(['hello', 'world!']) #error

sum(['hello', 'world!'], '') #error
copy
Output:
Traceback (most recent call last):   File "<string>", line 1, in <module> TypeError: unsupported operand type(s) for +: 'int' and 'str' [Finished in 0.010021449066698551s]