Single File

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
Meta

Problem

You are given feed, a list of content entries. Each entry is either an item or a sub-list of entries, and sub-lists can nest to any depth. Any value that is not a list is a single item. Return all the items as one flat list.

However deep the nesting, every voice arrives in its own turn.

Example 1

Input:

feed = [[1,2],[3,[4,5]],6]

Output:

[1,2,3,4,5,6]

Example 2

Input:

feed = ["top",["trending",["sports","tech"]],"latest"]

Output:

["top","trending","sports","tech","latest"]

Worked solution and explanation

feed is a tree written as lists: every sub-list is a branch, every other value is a leaf, and the answer is the leaves read left to right. The nesting has no fixed depth, so no fixed number of loops reaches the bottom. The statement defines an entry in terms of itself (an item, or a list of entries), and that is the signal for recursion: the function that flattens feed is the same function that flattens any sub-list inside it.

From nested entries to one flat feed

Step 1: Walk the top level in order

The output keeps items in the order you meet them reading left to right, so iterate feed front to back and grow result as you go.

Step 2: Ask the question the statement gives you

An item is any value that is not a list, so the test is isinstance(item, list) and nothing broader. Everything that fails it goes straight into result with append.

Step 3: Hand a sub-list back to flatten

A sub-list is a smaller feed. flatten(item) returns its items already flat, and result.extend(...) splices them in at the current position, which is what keeps 'trending' ahead of 'sports' and 'tech' ahead of 'latest'.

Step 4: Let the base case fall out of the loop

A list that holds only items never recurses: the loop appends each one and returns. An empty list returns []. The recursion stops there with no special branch written for it.

Recursive depth-first flattening
def flatten(feed):
    result = []
    for item in feed:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

Why flattening one level fails the first example

The first shortcut most people try is to splice each sub-list in once without recursing. It passes any feed whose sub-lists hold only items, and it fails the first example.

Flattens one level only
def flatten(feed):
    result = []
    for item in feed:
        if isinstance(item, list):
            result.extend(item)
        else:
            result.append(item)
    return result

On [[1, 2], [3, [4, 5]], 6] this returns [1, 2, 3, [4, 5], 6]: the inner [4, 5] survives as a list.

The same walk on your own stack

Recursion borrows Python's call stack, and CPython's default limit is 1,000 frames. If the nesting can run deeper than that, hold the pending entries in a list of your own. Push a sub-list's entries reversed so the leftmost one pops first and the output order stays the same.

Explicit stack, no recursion
def flatten(feed):
    result = []
    stack = feed[::-1]
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(item[::-1])
        else:
            result.append(item)
    return result

Returns the same list as the recursive version on both examples; each entry is pushed and popped once, and feed is left untouched because the slices are copies.

Common follow-up questions