sum()
Anonymous contributor
Published Jun 20, 2023
Contribute to Docs
The sum()
function takes in an iterable object, such as a list or tuple, and returns the sum of all elements.
Syntax
sum(iterable, start = 0)
iterable
: An object capable of returning its elements one at a time such as a list, tuple, or dictionary.start
: A number added to the sum of the numbers in the iterable.
Example 1
Summing up the elements of a list:
numbers = [1, 2, 3, 4, 5]total = sum(numbers)print(total)
This example results in the following output:
15
Example 2
Summing up the elements of a tuple:
prices = (10.99, 5.99, 8.49)total = sum(prices)print(total)
This example results in the following output:
25.47
Example 3
Using the start
parameter to specify an initial value for the sum:
numbers = [1, 2, 3, 4, 5]total = sum(numbers, 10)print(total)
This example results in the following output:
25
Codebyte Example
Summing up a list of lists (concatenation):
Note: The
sum()
function works with any iterable object that contains numbers or elements that can be added together.
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Skill path
Analyze Data with Python
Learn to analyze and visualize data using Python and statistics.Includes 8 CoursesWith CertificateIntermediate13 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours