The Deep Unpacker

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

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.

Boxes inside boxes. Eventually you reach the bottom.

Example 1

Input:

lst = [[1,[2,3]],[4,5]]

Output:

[1,2,3,4,5]

Example 2

Input:

lst = [[1,2,3]]

Output:

[1,2,3]

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
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

Common follow-up questions