50 XP

62. Sum a nested list

Intermediate recursion lists

Write a function nested_sum(items) that takes a list and returns the total of all the numbers in it. Each item is either a whole number or another list built the same way, so lists can sit inside lists to any depth: [1, [2, [3]]] holds 1, 2 and 3.

  • Add up the numbers at every depth.
  • An empty list, at any depth, adds nothing, so [] and [[], [[]]] both add up to 0.

A loop alone can't do this, because you don't know how deep the lists go. Each inner list is the same problem again, only smaller.

Example 1

Inputitems = [1, [2, 3], [[4]], 5]
Output15
Explanation1 + 2 + 3 + 4 + 5, from every depth.

Example 2

Inputitems = [[1, [2, [3, [4]]]]]
Output10
ExplanationFive lists deep, still 1 + 2 + 3 + 4.

Example 3

Inputitems = [[], [[]]]
Output0
ExplanationOnly empty lists: no numbers.

Constraints

  • items holds whole numbers from -1000 to 1000 and lists, nested at most 20 deep, with at most 100 numbers in all.

Submit also runs 7 more tests you can't see.

Practises Recursion (lesson 20).

Code
def nested_sum(items):
    """Add up the numbers in a nested list.

    items: list of ints and lists, nested to any depth
    Returns: int, the total of every number at every depth
    """
    # Write your code here
    pass