Skip to content

Python sum() function | sum of all items in an iterable

  • by

The python sum() function is used to sum all items in an iterable. Actually, this function adds the items of an iterable and returns the sum.

sum(iterable, start) 

Start parameter is an option to use and items of the given iterable from left to right. Where iterable objects (list, tuple, dict, etc) should be numbered.

Example sum function in Python

Simple example code sum of a given integer list.

a = [1, 2, 3, 4, 5]
res = sum(a, 7)

print(res)
print(type(res))

Output:

Python sum function

To add floating-point numbers with exact precision, then you should use math.fsum(iterable) instead.

Without start parameter

a = [1, 2, 3, 4, 5]
res = sum(a)

print(res)

Output: 15

You can use the sum() function with any iterable that contains numeric values. Keep in mind that it’s not limited to just integers; it can work with floats and other numeric types as well.

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading