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 tutorial, you will learn how to Display Prime Numbers Between Two Intervals using the if and else...
In this python tutorial, you will learn how to Calculate Standard Deviation with built in functions of the python programming...
In this Python program, we will convert temperature values from Celsius to Fahrenheit. The Celsius and Fahrenheit scales are two...