The Wayback Machine - https://web.archive.org/web/20240808042247/https://www.geeksforgeeks.org/sum-function-python/
Open In App

sum() function in Python

Last Updated : 28 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list.

Sum() Function in Python Syntax

Syntax : sum(iterable, start)

  • iterable : iterable can be anything list , tuples or dictionaries , but most importantly it should be numbers.
  • start : this start is added to the sum of  numbers in the iterable. If start is not given in the syntax , it is assumed to be 0.

Possible two more syntaxes

sum(a) : a is the list , it adds up all the numbers in the list a and takes start to be 0, so returning only the sum of the numbers in the list.
sum(a, start) : this returns the sum of the list + start The sum

The python provide in-built function like sum() in order to reduce the code length and programmer time there are many more in-built function that are important to learn if you wish to build your career in the field of the ML engineering our Complete Machine Learning & Data Science Program provide you with all these function and many more to build your strong foundation.

Python Sum() Function Examples

Get the sum of the list in Python .

Python
numbers = [1,2,3,4,5,1,4,5]

Sum = sum(numbers)
print(Sum)

Sum = sum(numbers, 10)
print(Sum)

Output:

25
35

Here below we cover some examples using the sum function with different datatypes in Python to calculate the sum of the data in the given input

  • Sum Function on a Dictionary
  • Sum Function on a Set
  • Sum Function on a Tuple
  • The sum in Python with For Loop
  • Error and Exceptions
  • Practical Application

Python Sum Function on a Dictionary

In this example, we are creating a tuple of 5 numbers and using sum() on the dictionary in Python.

Python
my_dict = {'a': 10, 'b': 20, 'c': 30}
total = sum(my_dict.values())
print(total)

Output :

60

Time complexity: O(1)
Space complexity: O(n)

Python Sum Function on a Set

In this example, we are creating a tuple of 5 numbers and using sum() on the set in Python.

Python
my_set = {1, 2, 3, 4, 5}
total = sum(my_set)
print(total) 

Output :

15

Python Sum Function on a Tuple

In this example, we are creating a tuple of 5 numbers and using sum() on the tuple in Python.

Python
my_tuple = (1, 2, 3, 4, 5)
total = sum(my_tuple)
print(total) 

Output :

15

Time complexity: O(1)
Space complexity: O(n)

The sum in Python with For Loop

In this, the code first defines a list of numbers. It then initializes a variable called total to 0. The code then iterates through the list using a for loop, and for each number in the list, it adds that number to the total variable. Finally, the code prints the total value, which is the sum of the numbers in the list.

Python
# Define a list of numbers
numbers = [10, 20, 30, 40, 50]

# Initialize a variable to store the sum
total = 0

# Iterate through the list and add each number to the total
for num in numbers:
    total += num

# Print the sum of the numbers
print("The sum of the numbers is:", total)

Output :

The sum of the numbers is: 150

Time complexity: O(n)
Space complexity: O(n)

Error and Exceptions

TypeError : This error is raised when there is anything other than numbers in the list . In the given example we are using a list of strings rather than an integer.

Python
arr = ["a"]

# start parameter is not provided
Sum = sum(arr)
print(Sum)

# start = 10
Sum = sum(arr, 10)
print(Sum)

Output :

Traceback (most recent call last):
File "/home/23f0f6c9e022aa96d6c560a7eb4cf387.py", line 6, in
Sum = sum(arr)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

Practical Application

Problems where we require the sum to be calculated to do further operations such as finding out the average of numbers.

Python
numbers = [1,2,3,4,5,1,4,5]

# start = 10
Sum = sum(numbers)
average= Sum/len(numbers) 
print (average)

Output

3


Previous Article
Next Article

Similar Reads

Prefix sum array in Python using accumulate function
We are given an array, find prefix sums of given array. Examples: Input : arr = [1, 2, 3] Output : sum = [1, 3, 6] Input : arr = [4, 6, 12] Output : sum = [4, 10, 22] A prefix sum is a sequence of partial sums of a given sequence. For example, the cumulative sums of the sequence {a, b, c, ...} are a, a+b, a+b+c and so on. We can solve this problem
1 min read
Numpy MaskedArray.sum() function | Python
numpy.MaskedArray.median() function is used to compute the sum of the masked array elements over the given axis. Syntax : numpy.ma.sum(arr, axis=None, dtype=None, out=None, keepdims=False) Parameters: arr : [ ndarray ] Input masked array. axis :[ int, optional] Axis along which the sum is computed. The default (None) is to compute the sum over the
3 min read
Sum 2D array in Python using map() function
Given a 2-D matrix, we need to find sum of all elements present in matrix ? Examples: Input : arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]] Output : Sum = 26 This problem can be solved easily using two for loops by iterating whole matrix but we can solve this problem quickly in python using map() function. C/C++ Code # Function to calculate sum of all el
2 min read
Map function and Dictionary in Python to sum ASCII values
We are given a sentence in the English language(which can also contain digits), and we need to compute and print the sum of ASCII values of the characters of each word in that sentence. Examples: Input : GeeksforGeeks, a computer science portal for geeksOutput : Sentence representation as sum of ASCII each character in a word: 1361 97 879 730 658 3
2 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples.  What is Calling a Function
5 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
4 min read
Create an array of size N with sum S such that no subarray exists with sum S or S-K
Given a number N and an integer S, the task is to create an array of N integers such that sum of all elements equals to S and print an element K where 0 ? K ? S, such that there exists no subarray with sum equals to K or (S - K). If no such array is possible then print "-1".Note: There can be more than one value for K. You can print any one of them
6 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
How to use the NumPy sum function?
NumPy's sum() function is extremely useful for summing all elements of a given array in Python. In this article, we'll be going over how to utilize this function and how to quickly use this to advance your code's functionality. Let's go over how to use these functions and the benefits of using this function rather than iteration summation. Let's fi
4 min read
Practice Tags :
three90RightbarBannerImg