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 Set difference_update()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Print Hello world!
Python map()
Python Set union()
Python String ljust()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python issubclass()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Add Two Numbers
Python Program to Make a Simple Calculator
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Find the Sum of Natural Numbers
Python Global Keyword
Python Program to Append to a File
Python Program to Display the multiplication Table
Python Program to Catch Multiple Exceptions in One Line
Python Program to Capitalize the First Character of a String
Python Program to Check Armstrong Number
Python String swapcase()
Python String zfill()
Python Multiple Inheritance
Python String lstrip()
Python String istitle()
Python Program to Access Index of a List Using for Loop
Python memoryview()
Python break and continue
Python Dictionary copy()
Python Dictionary values()
Python List remove()
Python Program to Differentiate Between del, remove, and pop on a List
Python bin()