Recursion · 14 / 18 Exercise Hard

Flattening nested lists

Objective

Lists can contain other lists at any depth. A fixed loop does not work to go through them: recursion follows the shape of the data.

Instructions

  • Read a line with a Python list written as JSON, for example [1, [2, [3, 4]], 5], and convert it with json.loads.
  • Define a recursive function that returns the flattened list, with all the numbers in the order in which they appear. Show Flattened: ... (the numbers separated by a space).
  • Define another recursive one that computes the depth: a list without sublists has depth 1 and, if there are sublists, it is 1 plus the greatest of their depths. Show Depth: d.
  • Use isinstance(item, list) to know whether an item is a list.
Input
[1, [2, [3, 4]], 5]
Output
Flattened: 1 2 3 4 5
Depth: 3

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise