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

Python’s recursion allows us to solve complex problems by breaking them down into simpler subproblems. In this illustration, we’ll delve into a Python program that employs recursion to determine the total sum of a nested list.

Problem Statement

Develop a Python program that calculates and presents the total sum of a given nested list. The program should use recursion to navigate through the nested structure, adding up all the individual elements, regardless of the depth of nesting.

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

def nested_list_sum(nested_list):
    total_sum = 0
    
    for element in nested_list:
        if isinstance(element, list):
            total_sum += nested_list_sum(element)
        else:
            total_sum += element
    
    return total_sum

# Input and Output
sample_nested_list = [1, [2, 3, [4, 5]], [6, [7]]]
total = nested_list_sum(sample_nested_list)
print("Nested List:", sample_nested_list)
print("Total Sum:", total)
Python Program to Find the Total Sum of a Nested List Using Recursion

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...