Python sum() Function Tutorial

  • Post author:
  • Post category:Python

In this section, we will learn what the sum() function is and how to use it in Python.

sum() Function in Python

The Python sum() function is used to sum the items of an iterable object.

For example, if the target iterable object is a list with integer numbers, then calling this function will add those numbers together and return the sum as a result.

Python sum() Function Syntax:

sum(iterable, initialValue)

Python sum() Function Parameters

The function takes two arguments:

  • The first argument is the iterable object that we want to sum its elements.
  • The second argument is the initial number that we want the elements of the iterable object to be added to. This value is optional and, if ignored, the default value, which is 0 will be used instead.

Python sum() Function Return Value

The return value of this method is the sum of all items in the target iterable object.

Example: sum() function in python

tuple1 = (1,2,3,4,5,6,7)

print(sum(tuple1))

Output:

28

Example: python sum list

list1 = [1,2,3,4,5,6,7]

print(sum(list1))

Output:

28

Example: sum() function and Python Dictionary

dictionary = {

0: "John",

1: "Doe",

2: 200

}

print(sum(dictionary))

Output:

3

Note that invoking the sum() function in a dictionary will sum up its keys!

Leave a Reply