Python Program to Find the Total Sum of a Nested List Using Recursion


When it is required to find the total sum of a nest list using the recursion technique, a user defined method is used, that takes the list as a parameter.

The recursion computes output of small bits of the bigger problem, and combines these bits to give the solution to the bigger problem.

A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).

Example

Below is a demonstration for the same −

 Live Demo

def recursion_sum(my_list):
   my_total = 0
   for elem in my_list:
      if (type(elem) == type([])):
         my_total = my_total + recursion_sum(elem)
      else:
         my_total = my_total + elem
   return my_total
my_list = [[2,3], [7,9], [11,45], [78,98]]
print("The list elements are :")
print(my_list)
print( "The sum is :")
print(recursion_sum(my_list))

Output

The list elements are :
[[2, 3], [7, 9], [11, 45], [78, 98]]
The sum is :
253

Explanation

  • A method named ‘recursion_sum’ is defined, with list as a paramteter.
  • Initially, a variable is assigned to 0.
  • The elements in the list are iterated over, and if their type matches, the elements in the list are added, and the method is called again.
  • Otherwise, the elements are just added to a variable.
  • This variable is displayed as output on the console.
  • Outside the function, the below operations take place −
  • The nested list is defined, and is displayed on the console.
  • The method is called by passing this list as a parameter.
  • The output is displayed on the console.

Updated on: 12-Mar-2021

397 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements