The Wayback Machine - https://web.archive.org/web/20240905155154/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
News Follow

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
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
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
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
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Python | Pandas Series.sum()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.sum() method is used to get the sum of the values for the requested axis. Syntax: Series.sum(axis=None, skipna=None, level
2 min read
Python | Pandas Series.cumsum() to find cumulative sum of a Series
Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements. Syntax: Series.cumsum(axis=None, skipna=True) Parameters: axis: 0 or 'index' for row wise operation and 1 or 'columns' for column wise operation skipna: Skip
2 min read
Python | Pandas dataframe.sum()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.sum() function return the sum of the values for the requested axis. If the input is index axis then it adds all the val
2 min read
Python | Pandas Panel.sum()
In Pandas, Panel is a very important container for three-dimensional data. The names for the 3 axes are intended to give some semantic meaning to describing operations involving panel data and, in particular, econometric analysis of panel data. Panel.sum() function is used to return the sum of the values for the requested axis. Syntax: Panel.sum(ax
2 min read
Python | Get sum of tuples having same first value
Given a list of tuples, the task is to sum the tuples having the same first value. Examples: Input: [(1, 13), (2, 190), (3, 82), (1, 12)] Output: [(1, 25), (2, 190), (3, 82)]Input: [(1, 13), (1, 190), (3, 25), (1, 12)] Output: [(1, 215), (3, 25)] Let us discuss the different ways we can do this task. Method #1: Using map() C/C++ Code # Python code
6 min read
Python | Numpy matrix.sum()
With the help of matrix.sum() method, we are able to find the sum of values in a matrix by using the same method. Syntax : matrix.sum() Return : Return sum of values in a matrix Example #1 : In this example we are able to find the sum of values in a matrix by using matrix.sum() method. # import the important module in python import numpy as np # ma
1 min read
Python | Find the number of unique subsets with given sum in array
Given an array and a sum, find the count of unique subsets with each subset's sum equal to the given sum value. Examples: Input : 4 12 5 9 12 9 Output : 2 (subsets will be [4, 5] and [9]) Input : 1 2 3 4 5 10 Output : 3 We will use dynamic programming to solve this problem and this solution has time complexity of O(n2). Below is dp[][] used in the
2 min read
Python | sort list of tuple based on sum
Given, a list of tuple, the task is to sort the list of tuples based on the sum of elements in the tuple. Examples: Input: [(4, 5), (2, 3), (6, 7), (2, 8)] Output: [(2, 3), (4, 5), (2, 8), (6, 7)] Input: [(3, 4), (7, 8), (6, 5)] Output: [(3, 4), (6, 5), (7, 8)] # Method 1: Using bubble sort Using the technique of Bubble Sort to we can perform the s
4 min read
Python program to find number of m contiguous elements of a List with a given sum
Given a list 'L', a sum 'S' and number of elements to take at a time 'm'. The task is to find how many ways sum s can be found by adding any m contiguous elements. Examples: Input : 1 2 1 3 2 3 2 Output : 2 Input : 1 1 1 1 1 1 3 2 Output : 0 For example 1, we have to find a sum 3 with the help of any 2 contiguous elements of the list. This can be d
4 min read
Cumulative sum of a column in Pandas - Python
Cumulative sum of a column in Pandas can be easily calculated with the use of a pre-defined function cumsum(). Syntax: cumsum(axis=None, skipna=True, *args, **kwargs)Parameters: axis: {index (0), columns (1)} skipna: Exclude NA/null values. If an entire row/column is NA, the result will be NAReturns: Cumulative sum of the column Example 1: C/C++ Co
2 min read
How to Compute the Sum of All Rows of a Column of a MySQL Table Using Python?
MySQL server is an open-source relational database management system that is a major support for web-based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. In order to access MySQL databases from a web server, we use various modules in Python such a
2 min read
Python Program to Get Sum of N Armstrong Number
Given a number N, determine the sum of the first N Armstrong numbers using Python. Example: Input : 11 Output : 568 First 11 Armstrong numbers are 1, 2, 3, 4, 5, 6, 7, 8, 9, lies to, 370 Their summation is 578Method 1: Using Iterative methodsCreate a while loop that breaks when the desired number of Armstrong numbers is found.At each iteration, the
3 min read
Python Program to Get Sum of cubes of alternate even numbers in an array
Given an array, write a program to find the sum of cubes of alternative even numbers in an array. Examples: Input : arr = {1, 2, 3, 4, 5, 6} Output : Even elements in given array are 2,4,6 Sum of cube of alternate even numbers are 2**3+6**3 = 224 Input : arr = {1,3,5,8,10,9,11,12,1,14} Output : Even elements in given array are 8,10,12,14 Sum of cub
5 min read
Python Program to Find the Maximum sum of i*arr[i] among all rotations of a given array
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29 {1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
6 min read
How to Calculate Residual Sum of Squares in Python
The residual sum of squares (RSS) calculates the degree of variance in a regression model. It estimates the level of error in the model's prediction. The smaller the residual sum of squares, the better your model fits your data; the larger the residual sum of squares, the worse. It is the sum of squares of the observed data minus the predicted data
2 min read
numpy.sum() in Python
This function returns the sum of array elements over the specified axis. Syntax: numpy.sum(arr, axis, dtype, out): Parameters: arr: Input array. axis: The axis along which we want to calculate the sum value. Otherwise, it will consider arr to be flattened(works on all the axes). axis = 0 means along the column and axis = 1 means working along the r
3 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Practice Tags :