Python sum() Function



The Python sum() function returns the sum of all numeric items in any iterable, such as list or tuple. It also accept an optional "start" argument which is 0 by default. If given, the numbers in the list are added to the start value.

Syntax

Following is the syntax for Python sum() function −

sum(iterable, start)

Parameters

The Python sum() function accepts the following parameters −

  • iterable − It represents an iterable with numeric operands.

  • start − It specifies the initial value of sum.

Return value

This function returns the sum of numeric operands in the iterable

Examples

Now, we will see some examples of sum() function −

Example 1

The Python sum() function accepts iterables like lists and tuples as an argument and displays the result in corresponding iterable after adding their elements as shown in the below code.

x = [10,20,30]
total = sum(x)
print ("x: ",x, "sum(x): ", total)

x = (10, -20, 10)
total = sum(x)
print ("x: ",x, "sum(x): ", total)

It will produce the following output

x: [10, 20, 30] sum(x): 60
x: (10, -20, 10) sum(x): 0

Example 2

The sum() function also accepts an optional argument, which is the starting value from which to begin the sum operation. In this example, we are passing the value of start as 5.

x = [10,20,30]
start = 5
total = sum(x, start)
print ("x: ",x, "start:", start, "sum(x, start): ", total)

On executing, the above code will produce the following output −

x:  [10, 20, 30] start: 5 sum(x, start):  65

Example 3

We can also use sum() function to add the values of a dictionary. To do so, we need to pass the dictionary values() method as an argument to sum().

newDict = {"valOne": 101, "valTwo": 201, "valThree": 301}
output = sum(newDict.values())
print("The sum of dictionary values:", output)

On executing the above code, it will produce the following result −

The sum of dictionary values: 603
python_built_in_functions.htm
Advertisements