Python sum() With Examples

Python sum() function is used to get the sum of numbers of an iterable.

Python sum()

Python sum() function syntax is:

start is an optional number with default value of 0. If start is provided, then the sum of start and all the numbers in the iterable is returned.

Python sum() list of numbers

Output:

Note that sum() method doesn’t take keyword arguments, so if we write sum([1, 2, 3], start=10) then it will throw exception as TypeError: sum() takes no keyword arguments.

Python sum of a sequence of integers

Since sum accepts iterable as argument, we can pass tuple, bytes of numbers too.

Output:

Python sum of floats

Output: 7.0

If you want to add floating point values with extended precision, you can use math.fsum() function.

Python sum of complex numbers

sum() function works with complex numbers too.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply