Python sum() function

The sum() function in Python is used when we need to find the sum of all items available in an iterable such as a list, tuple, etc. For example:

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

x = (12, 23, 34, 54)
print(sum(x))

The output is:

15
123

Python sum() function syntax

The syntax of the sum() function in Python is:

sum(iterable, value)

The "value" parameter is optional and is used when we need to add extra value to the result returned by sum().

Note: The iterable should contain numbers to perform the addition of all of its items using the sum() function.

Python sum() function example

Here is an example of the sum() function in Python:

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

print(sum(x))
print(sum(x, 5))
print(sum(x, 10))
print(sum(x, 100))
print(sum([1, 2, 3, 4, 5], 100))

x = {1: "Name", 2: "University", 3: "Course"}
print(sum(x))

The output is:

15
20
25
115
115
6

If you use the dictionary as an iterable, then its key will be used.

Advantages of the sum() function in Python

Disadvantages of the sum() function in Python

Python Online Test


« Previous Function Next Function »