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

You are given nested, a batch collector's output listed in the order the workers reported. Each item is one worker's report: most workers send a sublist of results, and some send a single bare result. Only the workers' grouping comes off, so a result inside a sublist that is itself a list stays whole. A bare result belongs in the merged list as-is. Return every result as one flat list.

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