Flatten a Nested List Practice Problem
This data science coding problem helps you practice Control Flow & Loops, flatten a nested list, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Control Flow & Loops.
- Problem ID: 79
- Problem key: 79-flatten-a-nested-list
- URL: https://datacrack.app/solve/79-flatten-a-nested-list
- Difficulty: medium
- Topic: Control Flow & Loops
- Module: Python Fundamentals
Problem Statement
# 🧩 Flatten a Nested List
---
### 🎯 Goal
Real-world data often arrives in nested structures — JSON responses, nested arrays from APIs, multi-level records. **Flattening** is the process of converting an arbitrarily nested structure into a single flat list.
This problem introduces **recursion** — a function calling itself — which is a key technique for tree-like data structures.
---
### 🔍 What is Flattening?
```
Input: [1, [2, 3], [4, [5, 6]]]
Output: [1, 2, 3, 4, 5, 6]
```
The nesting depth is **arbitrary** — there could be lists inside lists inside lists.
---
### 💻 Task
Implement `flatten(nested)` that recursively flattens a list of arbitrary depth.
---
### 📥 Input
- `nested`: a Python list that may contain integers or other nested lists at any depth
### 📤 Output
- A flat list of all integers in the original structure, in order
---
### 🧩 Starter Code
```python
def flatten(nested):
"""
Recursively flatten a nested list of arbitrary depth.
Args:
nested (list): A list that may contain ints or other lists
Returns:
list: All integers in a single flat list
"""
result = []
for item in nested:
# 🧠 TODO: If item is a list, recurse into it and extend result
# 🧠 TODO: If item is not a list, just append it
pass
return result
```
---
### 💡 Example
```python
flatten([1, [2, 3], [4, [5, 6]]])
# Expected: [1, 2, 3, 4, 5, 6]
flatten([[[1]], [[2, 3]], 4])
# Expected: [1, 2, 3, 4]
```
---
### 🔑 Key Concepts
- `isinstance(item, list)` — check if an item is a list
- `result.extend(...)` — add multiple elements to a list (vs `append` which adds one)
- Recursion: the function calls itself with a smaller problemStarter Code
def flatten(nested):
"""
Recursively flatten a nested list of arbitrary depth.
Args:
nested (list): A list that may contain ints or other lists
Returns:
list: All integers in a single flat list
"""
result = []
for item in nested:
# 🧠 TODO: If item is a list, recurse into it and extend result
# 🧠 TODO: If item is not a list, just append it
pass
return result