# The Lazy Unpacker

> Instead of loading it all at once, yield it one piece at a time.

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

Domain: Python · Difficulty: medium · Seniority: L4

## Problem

Given a list nested to arbitrary depth, implement a generator (or equivalent) that yields each non-list leaf value in order. The test harness collects the results into a list.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **recursive generator flattening** for memory-efficient processing of nested structures. It probes `yield from` syntax and the ability to distinguish between list and non-list elements during recursion.

---

### Break down the requirements

#### Step 1: Check if the current element is a list

If it is, recurse. If not, yield it.

#### Step 2: Use yield from for recursive delegation

`yield from flatten(item)` delegates to the recursive generator.

#### Step 3: Convert to list for testing

Wrap the generator call in `list()` to materialize results.

---

### The solution

**Recursive generator with yield from**

```python
def flatten_gen(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten_gen(item)
        else:
            yield item
def flatten(nested: list) -> list:
    result = list(flatten_gen(nested))
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the total number of leaf elements.
> 
> **Space:** O(d) for the generator chain where d is the maximum nesting depth. No intermediate lists are created.

> **Interviewers Watch For**
>
> Whether you use `yield from` for clean recursive delegation vs manually iterating the recursive result.

> **Common Pitfall**
>
> Using `yield flatten_gen(item)` instead of `yield from`. This yields the generator object itself, not its elements.

---

## Common follow-up questions

- What is the difference between yield and yield from? _(Tests that `yield from` delegates to a sub-generator, while `yield` produces a single value.)_
- How would you limit flattening to a specific depth? _(Tests adding a depth parameter that decrements on each recursive call.)_
- What if the nesting is extremely deep? _(Tests Python's recursion limit and the need for an iterative stack-based approach.)_

## Related

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