Flatten to a Depth
Advanced · Stretch · from Python Recursion: How It Works, When to Use It, and Examples
From the lesson: Python Recursion: How It Works, When to Use It, and Examples
Imagine a set of Russian nesting dolls. You open the biggest one and find a smaller one inside. Open that, and there's an even smaller one. You keep opening until you reach the tiniest doll that doesn't open - that's the end.
Read the lessonWrite a recursive function flatten(items, depth) that takes a list which may hold lists inside lists, and opens the inner lists only depth levels deep. A depth of 1 opens the lists directly inside items; their own inner lists stay as they are.
flatten([1, [2, [3, [4]]]], 1) # [1, 2, [3, [4]]]
flatten([1, [2, [3, [4]]]], 2) # [1, 2, 3, [4]]With a depth of 0 nothing is opened, and a depth bigger than the nesting flattens everything. Return a new list. Some of the tests are hidden.
What Check runs
Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.
| Runs | Expected output |
|---|---|
| flatten([1, [2, [3, [4]]]], 1) | [1, 2, [3, [4]]] |
| flatten([1, [2, [3, [4]]]], 2) | [1, 2, 3, [4]] |
More Recursion exercises
- Predict Recursive OutputBeginner
- Recursive Sum 1 to NBeginner
- Fix the Broken Power FunctionIntermediate
- Recursive FibonacciIntermediate
- Reverse a String RecursivelyIntermediate
- Count Digits RecursivelyAdvanced
All Python exercises · 50 practice problems · Functions quiz