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.
def flatten(feed):
result = []
for item in feed:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return resultWhy 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.
def flatten(feed):
result = []
for item in feed:
if isinstance(item, list):
result.extend(item)
else:
result.append(item)
return resultOn [[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.
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 resultReturns 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
- What do you return for an empty
feed, or for one like[[], [[]]]?[]in both cases, because an empty list runs the loop 0 times and hands nothing to its caller'sextend. Real feeds have empty sections all the time, and a version that peeks atfeed[0]before looping is the one that crashes on them. - The feed arrives nested 50,000 levels deep. What happens?
The recursive version raises
RecursionErrorlong before it reaches the bottom, while the explicit-stack version finishes because its depth lives in an ordinary list. Nesting that deep usually comes from machine-generated JSON, where nobody promised you a sane depth. - The flat feed has millions of items and the consumer reads them one at a time. Do you still build the list?
Turn
flatteninto a generator:yield itemfor a leaf andyield from flatten(item)for a sub-list, so memory holds only the current path through the nesting. That matters when the next stage is a writer or a paginator that never needs the whole list at once. - A tuple shows up inside
feed. Does it get flattened?It stays whole: any value that isn't a list is one item, so
(1, 2)comes out as a single entry. If the rule later widens to tuples, the change isisinstance(item, (list, tuple)), and it should ship with a test that a string still comes out intact.