Python sum() Function Tutorial

Python provides the sum() function in order to sum multiple items or multiple variables or list items in an easy way. The sum() function is very similar to the Microsoft Excel SUM() macro. In this tutorial, we examine how to sum up these different scenarios.

sum() Function Syntax

The sum() function syntax is like below which simply accepts 2 parameters where 1 of them is optional.

sum(ITERABLE,START)
  • ITERABLE is a list of multiple values or variables.
  • START is an optional parameter and if specified the sum operation is started from this index for the ITERABLE.

Sum Multiple Items

The sum() function can be used to sum multiple items which is actually a list. We may provide these items one by one like below.

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

print(r)

Sum List

We can also provide an existing list without providing items one by one. In the following example, we provide the list named numbers .

numbers = [1,2,3,4,5]

r = sum( numbers )

print(r)

Sum From Specified Index

The sum() function can also sum numbers from the list by starting from the specified index number. In the following example, we start summing from index number 3.

numbers = [1,2,3,4,5]

r = sum( numbers ,3 )

print(r)

Leave a Comment