- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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).
Below is a demonstration for the same −
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))
The list elements are : [[2, 3], [7, 9], [11, 45], [78, 98]] The sum is : 253
- 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.
- Python Program to Flatten a Nested List using Recursion
- Python Program to Find the Length of a List Using Recursion
- Python Program to Find the Length of the Linked List using Recursion
- Python Program to Find the Length of the Linked List without using Recursion
- C# program to find the sum of digits of a number using Recursion
- Java Program to Find the Sum of Natural Numbers using Recursion
- Java Program to Find Sum of Digits of a Number using Recursion
- C++ program to Find Sum of Natural Numbers using Recursion
- Java Program to Find Sum of N Numbers Using Recursion
- Python Program to Find the Sum of Digits in a Number without Recursion
- Python Program to Flatten a List without using Recursion
- Python program to find Cumulative sum of a list
- Python Program to Find the Fibonacci Series Using Recursion
- How to Find Sum of Natural Numbers Using Recursion in Python?