# Deep Flatten

> Nested deep. Flatten everything.

Canonical URL: <https://datadriven.io/problems/deep_flatten>

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a list that may contain other lists nested to arbitrary depth, return a single flat list of all leaf values in left-to-right order. Non-list values are leaves; strings are leaves (do not iterate into them).

## Worked solution and explanation

### Why this problem exists in real interviews

Recursively flattening nested lists tests **recursion**, **type checking with isinstance**, and **accumulator patterns**. It is a classic problem that reveals whether a candidate can reason about arbitrary nesting depth.

> **Trick to Solving**
>
> For each element, check if it is a list. If so, recurse into it. If not, it is a leaf value to collect. A stack-based iterative approach also works and avoids Python's recursion limit for extreme depths.

---

### Break down the requirements

#### Step 1: Check if an element is a list or a leaf

Use `isinstance(item, list)` to distinguish containers from leaf values.

#### Step 2: Recurse into nested lists

For list elements, recursively flatten and extend the result.

#### Step 3: Collect leaf values in order

Append non-list elements directly to the result, preserving left-to-right traversal order.

---

### The solution

**Recursive flatten with isinstance check**

```python
def deep_flatten(nested):
    result = []
    for item in nested:
        if isinstance(item, list):
            flattened = deep_flatten(item)
            for val in flattened:
                result.append(val)
        else:
            result.append(item)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the total number of leaf elements across all nesting levels. Each leaf is visited exactly once.
> 
> **Space:** O(n + d) where d is the maximum nesting depth (recursion stack) and n is the output size.

> **Interviewers Watch For**
>
> Whether you use `isinstance(item, list)` rather than `type(item) == list`. The isinstance check is more Pythonic and handles subclasses. Mentioning the recursion depth limit shows systems awareness.

> **Common Pitfall**
>
> Treating strings as iterable and recursing into individual characters. Strings pass the iterable check, so you must specifically check for `list` (or exclude `str`).

---

## Common follow-up questions

- What if the nesting depth could exceed Python's recursion limit? _(Tests iterative flattening with an explicit stack.)_
- How would you handle dicts nested inside lists? _(Tests refining the isinstance check to flatten only list types, not dict types.)_
- What if you needed to also flatten tuples and sets? _(Tests using `isinstance(item, (list, tuple, set))` or a more general iterable check.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/deep_flatten)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.