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

This is a Python Program to find the total sum of a nested list using recursion.

Problem Description

The program takes a nested list and finds the total sum of the nested list using recursion.

Problem Solution

1. Initialize a variable to a nested list.
2. Pass the list as an argument to a recursive function to find the sum of elements of the list.
3. In the function, use a for loop and recursion to obtain the elements inside the sublists and store the summed up elements in a variable.
4. Return the total sum of the elements.
5. Print the sum of the nested list.
6. Exit.

Program/Source Code

Here is source code of the Python Program to find the sum of a nested list using recursion. The program output is also shown below.

def sum1(lst):
    total = 0
    for element in lst:
        if (type(element) == type([])):
            total = total + sum1(element)
        else:
            total = total + element
    return total
print( "Sum is:",sum1([[1,2],[3,4]]))
Program Explanation

1. A variable is initialized to a nested list.
2. The list is passed as an argument to a recursive function to find the sum of elements of the list.
3. In the function, A for loop and repeated recursion to obtain the elements inside the sublists.
4. The total sum of the elements is found out and is returned.
5. The sum of the elements in the nested list is printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1:
Sum is: 10

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.