
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
sum() function in Python
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
# 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
# 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
# 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.
- Related Questions & Answers
- Prefix sum array in python using accumulate function
- Sum 2D array in Python using map() function
- Prefix sum array in python using the accumulate function
- Map function and Dictionary in Python to sum ASCII values
- Two Sum in Python
- Path Sum in Python
- Combination Sum in Python
- Evaluate the sum of rows using the eval() function – Python Pandas
- Minimum Path Sum in Python
- How can we use MySQL SUM() function?
- MySQL SUM function to add decimal values
- Python - Prefix sum list
- Iterator function in Python
- Calendar function in Python
- Function Annotations in Python
Advertisements