Practice: Flatten a List
Lists inside lists.
Here's a list with lists inside it, and more lists inside those. Turn it into one flat list of numbers. You don't know how deep it goes. Pause. Why is this perfect for recursion?

- Lists inside lists
- Unknown depth
- Flatten it
Recursion handles any depth
For each item, if it's a list, we flatten it with the same function, and add all of its results. If it's a plain number, we add the number. The base case is hidden in there. A list with no inner lists simply never recurses. Run it. Every number, in order, however deep it was.
def flatten(items):
result = []
for item in items:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result
print(flatten([1, [2, [3, 4]], [[5]], 6]))[1, 2, 3, 4, 5, 6]
Natural fits for recursion
Recursion shines when the data is shaped like itself. Folders contain folders. Lists contain lists. And trees contain smaller trees. For those, recursion is often the simplest code you can write. For a plain row of items, a loop is usually better.
| key | value |
|---|---|
| Folders | inside folders |
| Nested lists | inside lists |
| Trees | made of smaller trees |
| Plain rows | just use a loop |
Summary
When data is nested inside itself, recursion handles any depth naturally. Next, a new section. Searching, starting with binary search.
Key takeaways- Is it a list? Recurse
- Otherwise, keep it
- Any depth