# Flatten the Nest

> Mixed nesting. One flat list out.

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

Domain: Python · Difficulty: easy · Seniority: L5

## Problem

Given a list containing integers and/or one-level-nested lists of integers, return a flat list of all integers in order.

## Worked solution and explanation

### Why this problem exists in real interviews

Single-level flattening tests whether you can distinguish between scalar elements and nested lists, applying `extend` vs. `append` correctly. It is a simplified version of deep flattening that checks basic type checking.

---

### Break down the requirements

#### Step 1: Iterate through the top-level list

Each element is either an integer or a one-level nested list of integers.

#### Step 2: Extend for lists, append for scalars

If the element is a list, add all its items to the result. Otherwise, add the element directly.

---

### The solution

**Single-level flatten with type branching**

```python
def flat_map(items):
    result = []
    for item in items:
        if isinstance(item, list):
            for sub in item:
                result.append(sub)
        else:
            result.append(item)
    return result
```

> **Time and Space Complexity**
>
> **Time:** O(n) where n is the total number of elements after flattening.
> 
> **Space:** O(n) for the result list.

> **Interviewers Watch For**
>
> Using `isinstance(item, list)` rather than `type(item) == list`. The isinstance approach handles subclasses and is considered more Pythonic.

> **Common Pitfall**
>
> Using `result += item` when item is a list. While this works, it creates a new list object on each iteration, which is less efficient than `extend` or an inner loop.

---

## Common follow-up questions

- What if items could contain tuples as well as lists? _(Tests broadening isinstance to check for both types.)_
- How would you handle None values in the nested lists? _(Tests whether None should be included as a leaf or filtered out.)_
- What if you needed to flatten exactly two levels deep? _(Tests applying the flattening logic twice or generalizing with a depth parameter.)_

## Related

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