Table of Contents
In this tutorial, we will learn about the Python sum() method with the help of examples.
The sum() function adds the items of an iterable and returns the sum.
Example
marks = [65, 71, 68, 74, 61] # find sum of all marks total_marks = sum(marks) print(total_marks) # Output: 339
1. sum() Syntax
The syntax of the sum() function is:
sum(iterable, start)
The sum() function adds start and items of the given iterable from left to right.
2. sum() Parameters
- iterable – iterable (list, tuple, dict, etc). The items of the iterable should be numbers.
- start (optional) – this value is added to the sum of items of the iterable. The default value of start is 0 (if omitted)
3. sum() Return Value
sum() returns the sum of start and items of the given iterable.
4. Example: Working of Python sum()
numbers = [2.5, 3, 4, -5] # start parameter is not provided numbers_sum = sum(numbers) print(numbers_sum) # start = 10 numbers_sum = sum(numbers, 10) print(numbers_sum)
Output
4.5 14.5
If you need to add floating-point numbers with exact precision, then you should use math.fsum(iterable) instead.
If you need to concatenate items of the given iterable (items must be strings), then you can use the join() method.
'string'.join(sequence)
Visit this page to learn about, Python join() Method
Related posts:
Python Program to Transpose a Matrix
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python List Comprehension
Python Program to Shuffle Deck of Cards
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python round()
Python chr()
Python super()
Python Program to Return Multiple Values From a Function
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Catch Multiple Exceptions in One Line
Python String islower()
Python Program to Check If Two Strings are Anagram
Python Tuple
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python String expandtabs()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python List extend()
Python Program to Compute the Power of a Number
Python String rindex()
Python String maketrans()
Python RegEx
Python Set issubset()
Python Program to Count the Number of Digits Present In a Number
Python Program to Add Two Matrices
Python dir()
Python Program to Calculate the Area of a Triangle
Python List clear()
Python property()
Python Sets
Python hash()
Python String rsplit()