Exercise: Flatten

Nested lists are the classic recursion warm-up, and a common phone-screen question.

Exercise: write flatten, which takes a list whose items are numbers or more lists, nested to any depth, and returns one flat list of the numbers in order.

flatten([1, [2, [3, 4]], 5])  # [1, 2, 3, 4, 5]
flatten([[], [[]]])           # []
  • Base case: an item that isn't a list goes straight into the result.
  • Recursive case: flatten the inner list and add its items with extend.
  • Use isinstance(item, list) to tell the two apart.
  • Don't change the input list.

Follow-up an interviewer might ask: what if the nesting is 10,000 levels deep? Then recursion hits the limit, and you would use a loop with an explicit stack. You don't need that here.

Press Check to run the tests.