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 String split()
Python vars()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Count the Number of Occurrence of a Character in String
Python frozenset()
Python Exception Handling Using try, except and finally statement
Python Tuple count()
Python Program to Find Factorial of Number Using Recursion
Python Data Types
Python Statement, Indentation and Comments
Python Program to Find the Factors of a Number
Python Program to Extract Extension From the File Name
Python Dictionary pop()
Python Set copy()
Python break and continue
Python String isalpha()
Python Set add()
Python Closures
Python Set intersection_update()
How to Get Started With Python?
Python timestamp to datetime and vice-versa
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python String isalnum()
Python Directory and Files Management
Python callable()
Python Set difference()
Python Program to Create Pyramid Patterns
Python range()
Python Keywords and Identifiers
Python dir()
Python Matrices and NumPy Arrays
Python Program to Transpose a Matrix