sum() function in Python

PythonServer Side ProgrammingProgramming

In this tutorial, we are going to learn about the sum() function.

The function sum() is used to sum all the numbers in an iterable. Let's see some examples.

Example

Live Demo

# initialinzing a list
numbers = [1, 2, 3, 4, 5]
# printing the sum
print(sum(numbers))

Output

If you run the above code, then you will get the following result.

15

The sum() takes one optional argument i.e., start that will be added to the result. Let's see it.

Example

Live Demo

# initialinzing a list
numbers = [1, 2, 3, 4, 5]
# printing the sum
print(sum(numbers, 5))

Output

If you run the above code, then you will get the following result.

20

If we place any string or any other data type inside the iterable, then we will get an error. Let's see it with the following example.

Example

Live Demo

# initialinzing a list
numbers = [1, 2, 3, [1, 2, 3], '5']
# printing the sum
print(sum(numbers, 5))

Output

If you run the above code, then you will get the following result.

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-40c38246060a> in <module>
3
4 # printing the sum
----> 5 print(sum(numbers, 5))
TypeError: unsupported operand type(s) for +: 'int' and 'list'

Conclusion

If you have any doubts in the tutorial, mention them in the comment section.

Published on 11-Jul-2020 08:01:41