Exercise 2 continued

Previous part
[
 27,
 38,
 22,
 [42,
  [[18,
    47,
    [13,
     49,
     [26, 16, [[43, [8, 16, 35, 31, 46], 12], 19], 14, [[27], 36, 40, 44]]]]],
  [23, [38, 26, 5, 14], 25, 8, 12],
  24,
  39]]

Our input is a list, so a good place to start is with a for loop. Here is a function that finds the sum of a list that contains only numbers.

def number_sum(numbers):
  total = 0
  for n in numbers:
    total += n
  return total

What if the list can contain numbers, or lists that contain numbers?

def number_sum(numbers):
  total = 0
  for n in numbers:
    if isinstance(n, int):
      total += n

    elif isinstance(n, list):
      for m in n:
        total += m

  return total

Not bad. We iterate over the outer list, and any time we find another list, we iterate over that one in an inner for loop. What if the inner lists can also contain lists of numbers?

def number_sum(numbers):
  total = 0
  for n in numbers:
    if isinstance(n, int):
      total += n

    elif isinstance(n, list):
      for m in n:
        if isinstance(m, int):
          total += m

        elif isinstance(m, list):
          for o in m:
            total += o

  return total

Still manageable, but that nesting is a bit uncomfortable. What if the innermost lists can also contain lists? What if those lists can contain lists? What if those lists can contain lists? We're going to run out of letters for our variables!

If you don't have a working solution yet, spend a few more minutes trying to write one.

Hint: Notice how the structure of the inner loops resembles the structure of the outer loops.

When you are ready to see the solution, click here.