  sum () function in python

Python Methods and Functions

The sum of the numbers in the list is required everywhere. Python provides a built-in function sum () that sums the numbers in a 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.

Two syntaxes are possible:

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 implementation of sum () in Python

 # Python code to demonstrate how it works # sum ()   numbers = [ 1 , 2 , 3 , 4 , 5 , 1 , 4 , 5 ]   < code class = "comments"> # no launch parameter specified Sum = sum (numbers) print ( Sum )   # start = 10 Sum = sum (numbers, 10 ) print ( Sum )

Output:

25 35

Errors and exceptions

error type: this error occurs if the list contains something other than digits.

 # Python code to demonstrate the exception # sum () arr = [ "a" ]   # no launch parameter specified Sum = sum (arr) print ( Sum )   # start = 10 Sum = 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 must contain numbers

Practical Application: problems when we need to calculate the amount to perform further operations, such as determining the average.

 # Python code to demonstrate practical use Amount # ()    nu mbers = [ 1 , 2 , 3 , 4 , 5 , 1 , 4 , 5 ]   # start = 10 Sum = sum (numbers) average = Sum / len (numbers)  p rint average

Output:

3