Open In App

sum() function in Python

Last Updated : 14 Aug, 2023
Improve
Improve
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

Python Sum() Function Examples

Get the sum of the list in Python.

Python3




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.

Python3




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.

Python3




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.

Python3




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.

Python3




# 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. 

Python3




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. 

Python3




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

Python - Test if Values Sum is Greater than Keys Sum in dictionary
Given a Dictionary, check if the summation of values is greater than the keys sum. Input : test_dict = {5:3, 1:3, 10:4, 7:3, 8:1, 9:5} Output : False Explanation : Values sum = 19 < 40, which is key sum, i.e false.Input : test_dict = {5:3, 1:4} Output : True Explanation : Values sum = 7 > 6, which is key sum, i.e true. Method #1: Using loop I
8 min read
Python | Ways to sum list of lists and return sum list
The list is an important container and is used almost in every code of day-day programming as well as web development, more it is used, the more is the requirement to master it and hence knowledge of its operations is necessary. Given a list of lists, the program to suppose to return the sum as the final list. Let's see some of the methods to sum a
5 min read
Sum all Items in Python List without using sum()
In Python, summing all the elements of a list is a common task, and while the `sum()` function simplifies the process, you can also implement the summation manually using a loop. By iterating through each element in the list and accumulating the total, you can achieve the same result without relying on the built-in `sum()` function. This alternativ
3 min read
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
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
4 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
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
3 min read
Practice Tags :