sum() function in Python
Sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list.
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 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
Below is the Python implementation of the sum()
Python3
# Python code to demonstrate the working of# sum() numbers = [1,2,3,4,5,1,4,5]# start parameter is not providedSum = sum(numbers)print(Sum)# start = 10Sum = sum(numbers, 10)print(Sum) |
Output:
25 35
Error and Exceptions
TypeError : This error is raised in the case when there is anything other than numbers in the list.
Python3
# Python code to demonstrate the exception of# sum()arr = ["a"]# start parameter is not providedSum = sum(arr)print(Sum)# start = 10Sum = sum(arr, 10)print(Sum) |
Runtime Error :
Traceback (most recent call last):
File "/home/23f0f6c9e022aa96d6c560a7eb4cf387.py", line 6, in
Sum = sum(arr)
TypeError: unsupported operand type(s) for +: 'int' and 'str'So the list should contain numbers Practical Application: Problems where we require sum to be calculated to do further operations such as finding out the average of numbers.
Python3
# Python code to demonstrate the practical application# of sum()numbers = [1,2,3,4,5,1,4,5]# start = 10Sum = sum(numbers)average= Sum/len(numbers)print (average) |
Output:
3
using 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 value of total, which is the sum of the numbers in the list.
Python3
# Define a list of numbersnumbers = [10, 20, 30, 40, 50]# Initialize a variable to store the sumtotal = 0# Iterate through the list and add each number to the totalfor num in numbers: total += num# Print the sum of the numbersprint("The sum of the numbers is:", total) |
The sum of the numbers is: 150
The time complexity of this approach is O(n), where n is the number of elements in the list. The sum() function iterates through the list once to calculate the sum.
The auxiliary space is O(1), as the only additional memory used is for the total variable, which is a constant amount of memory.



Please Login to comment...