# The Flat Mapper

> Nested values. One flat stream out.

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

Domain: Python · Difficulty: medium · Seniority: L3

## Problem

Given a list containing integers and/or flat lists of integers (one level of nesting only), return a single flat list of all integers in order. Do not recurse into deeper nesting (none will be present).

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **single-level list flattening**, distinguishing it from deep recursive flattening. It probes whether a candidate can handle mixed types (integers and lists) in a single pass.

---

### Break down the requirements

#### Step 1: Iterate through the input list

Each element is either an integer or a list of integers.

#### Step 2: Extend or append based on type

If the element is a list, add each of its items. If it is an integer, add it directly.

---

### The solution

**Single-level conditional flattening**

```python
def flat_map(items: list) -> list:
    result = []
    for item in items:
        if isinstance(item, list):
            for val in item:
                result.append(val)
        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 output list.

> **Interviewers Watch For**
>
> Whether you use `isinstance(item, list)` correctly. Using `type(item) == list` is fragile if subclasses are involved.

> **Common Pitfall**
>
> Recursing into nested lists. The problem specifies only one level of nesting, so recursion is unnecessary and could flatten too deeply.

---

## Common follow-up questions

- What if nesting could be arbitrarily deep? _(Tests upgrading to recursive flattening.)_
- How does this relate to `itertools.chain.from_iterable`? _(Tests knowledge of the standard library equivalent.)_
- What if elements could be tuples as well as lists? _(Tests broadening the isinstance check to `(list, tuple)`.)_

## Related

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