Explode List

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
Asked in
Tata Consultancy Services

Problem

Merge a batch collector's output in nested into one flat list of results, unwrapping only the top layer of grouping: a result that is itself a list stays whole. The on-call engineer doing this sees most workers report a sublist of results, while some report a single bare result that belongs in the merged list as-is.

One row holds many values. Unpack it.

Example 1

Input:

nested = [[101,102],103,[104,105]]

Output:

[101,102,103,104,105]

Example 2

Input:

nested = [[7,8],[],[9]]

Output:

[7,8,9]

Worked solution and explanation

Why this problem exists in real interviews

One-level list flattening tests whether you understand the difference between shallow and deep flattening. It checks that you extend sublists without recursing into deeper nesting.


Break down the requirements

Step 1: Check if each element is a list

For elements that are lists, extend the result with their contents. For non-list elements, append directly.

Step 2: Do not recurse

Only flatten one level. If a sublist contains another list, that inner list remains as-is.


The solution

Single-level flatten with isinstance check
def flatten(nested):
    result = []
    for item in nested:
        if isinstance(item, list):
            for sub in item:
                result.append(sub)
        else:
            result.append(item)
    return result

Common follow-up questions