Menu
Coddy logo textTech

Recap - Sum Nested List

Part of the Logic & Flow section of Coddy's Python journey — lesson 62 of 78.

challenge icon

Challenge

Easy

Write a recursive function named sum_nested that takes a nested list nested_list as an argument. The function should:

  1. Add all the integers in the list, including integers in any sublists.
  2. Return the total sum as an integer.

You can check if an element is a list using isinstance(element, list)

Example Input:

nested_list = [1, [2, 3], [4, [5, 6]], 7]

Example Output:

28

Try it yourself

def sum_nested(nested_list):
    total = 0
    for element in nested_list:
        if isinstance(element, list):  # Check if the element is a list
            # TODO: Recursively call sum_nested on the sublist and add to total
            pass
        else:
            # TODO: Add the integer directly to total
            pass
    return total

All lessons in Logic & Flow