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

When working with nested lists, we often need to calculate the sum of all elements regardless of their depth. Recursion is an elegant technique where a function calls itself to solve smaller parts of the problem until reaching a base case.

Recursion breaks down complex nested structures by processing each element. If an element is a list, the function calls itself recursively. If it's a number, it adds to the total sum.

Syntax

def recursive_sum(nested_list):
    total = 0
    for element in nested_list:
        if isinstance(element, list):
            total += recursive_sum(element)  # Recursive call
        else:
            total += element  # Base case
    return total

Example

Let's find the sum of all numbers in a nested list ?

def recursion_sum(my_list):
    my_total = 0
    for elem in my_list:
        if isinstance(elem, list):
            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

How It Works

The function processes each element:

  • Base case: If element is a number, add it to the total
  • Recursive case: If element is a list, call the function recursively
  • Each recursive call handles one level of nesting
  • Results bubble up and combine to give the final sum

Example with Deeper Nesting

Here's an example with multiple levels of nesting ?

def recursion_sum(my_list):
    my_total = 0
    for elem in my_list:
        if isinstance(elem, list):
            my_total = my_total + recursion_sum(elem)
        else:
            my_total = my_total + elem
    return my_total

nested_data = [1, [2, [3, 4]], 5, [6, 7]]
print("Nested list:", nested_data)
print("Total sum:", recursion_sum(nested_data))
Nested list: [1, [2, [3, 4]], 5, [6, 7]]
Total sum: 28

Key Points

  • Use isinstance(elem, list) to check if element is a list
  • Each recursive call processes one nesting level
  • Base case prevents infinite recursion
  • Works with any depth of nesting

Conclusion

Recursion elegantly handles nested lists by breaking the problem into smaller parts. The function calls itself for sublists and adds numbers directly, making it perfect for unknown nesting depths.

Updated on: 2026-03-25T17:36:33+05:30

736 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements