Finding sum of all numbers in list – Python

Lets take a problem statement stating : Take a LIST of integers and find SUM of the numbers of the list.Suppose that you want to calculate the sum of a list of numbers such as: [1,2,3,4,5].In normal mathematical form,we might have solve this problem by using the addition rule of adding a pair of numbers.We might have converted the list into fully parenthesized expression


and solved it using parenthesis rule to get the total of 15.

Now think how can we solve it using a python program?We can solve it using two ways.

Solution 01:

def function1(list1):
        for i in list1:


                        The function uses variable theSum to get total of all the numbers in the list by starting with 0 and adding each number in the list.

Solution 02:

def listsum(list1):

      if len(list1) == 1:

           return list1[0]


           return list1[0] + listsum(list1[1:])



This is a recursive algorithm.Here list1 is the sum of the first element of the list (i.e list1[0]) and the sum of rest of the numbers in the list(i.e list1[1:]).


In the code,in line 2 we are checking if the list contains only one element.This is necessary to check because by knowing this we can escape from the function.The sum of the list containinig only one number is the number in the list.

On line 5 of the code function calls itself.This is called recursive function.A recursive function is a function that calls itself.This makes our code more simple.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s