Editor

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 lesson

Write 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.

def flatten(items, depth):
pass
Solution unlocks after your first Check

What Check runs

Your code runs first, then each of these lines, and 5 more that stay hidden. The output must match exactly.

RunsExpected output
flatten([1, [2, [3, [4]]]], 1)[1, 2, [3, [4]]]
flatten([1, [2, [3, [4]]]], 2)[1, 2, 3, [4]]

More Recursion exercises

All Python exercises · 50 practice problems · Functions quiz