# The Deep Unpacker

> Boxes inside boxes. Eventually you reach the bottom.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list nested to arbitrary depth containing integers and/or inner lists, return a single flat list of all integers in left-to-right order.

## Worked solution and explanation

### Why this problem exists in real interviews

Recursive flattening is the clearest signal an interviewer has for whether you can reason about base cases, recursion depth, and order preservation. It also opens the door to iterative-with-stack follow ups that test whether you understand Python's recursion limit.

---

### Break down the requirements

#### Step 1: Pick the right type predicate

Use `isinstance(item, list)` rather than `hasattr(item, '__iter__')`. Strings, tuples, and dicts are iterable too, and the spec only nests lists. Being explicit avoids treating a stray string as a sequence of characters.

#### Step 2: Recurse on lists, append on integers

For each element, if it is a list, recurse and `extend` the result. Otherwise append. Iterating left to right preserves the required order for free.

#### Step 3: Decide between recursion and an explicit stack

Recursion is the cleanest expression. If the interviewer probes deep nesting (think 10000 levels), switch to an iterative stack so you do not blow Python's default recursion limit of 1000.

---

### The solution

**Recursive flatten preserving order**

```python
def flatten_nested(lst: list) -> list:
    result = []
    for item in lst:
        if isinstance(item, list):
            result.extend(flatten_nested(item))
        else:
            result.append(item)
    return result
```

> **Cost Analysis**
>
> Time is O(n) where n is the total count of leaf integers across all nesting levels because each element is visited once. Space is O(n) for the output plus O(d) recursion frames where d is the maximum nesting depth.

> **Interviewers Watch For**
>
> Whether you use `extend` instead of `append` on the recursive call, whether you guard against non list iterables, and whether you mention Python's recursion limit before they ask.

> **Common Pitfall**
>
> Calling `result.append(flatten_nested(item))` instead of `extend` produces a list of lists rather than a flat list. The unit test will fail on the first nested input even though the code looks correct.

---

## Common follow-up questions

- How would you flatten without recursion? _(Use an explicit stack and pop from the right. Discuss why pushing items in reverse order preserves left to right output.)_
- How would you handle tuples as well as lists? _(Switch the predicate to `isinstance(item, (list, tuple))`. Mention that strings are deliberately excluded even though iterable.)_
- How would you turn this into a generator? _(`yield` leaves and `yield from flatten_nested(item)` for nested lists. This avoids building the intermediate list and is what the lazy stream variant of this problem expects.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_deep_unpacker)
- [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.