Unnest Deeply Nested Lists Without Recursion
Stacks & QueuesAuto-graded · 16 test casesLast updated
Flatten an arbitrarily nested Python list into a single list in left-to-right order, treating only lists as containers and handling very deep nesting safely.
Unnest a Nested List
You are given a list items whose elements are either plain values or further lists, which may themselves contain lists, to any depth. Produce a single flat list holding every non-list value, in the order in which the values appear when the structure is read from left to right.
Rules
- Only objects of type
listcount as nested containers. Every other value is a leaf and must be copied to the result unchanged. This includes strings, tuples, dictionaries, numbers, booleans andNone. - Leaves are never dropped, even if they are falsy (
0,"",False,None). - Empty lists contribute nothing to the result, no matter how deeply they are nested.
- The result must be a new list. The input must not be modified.
- Nesting can be extremely deep, so a solution that relies on ordinary recursion may exceed Python's recursion limit. Your solution should work for such inputs.
- The input never contains a list that (directly or indirectly) contains itself.
Input
items: a list of arbitrary values, possibly containing nested lists.
Output
- A flat list of all leaf values in left-to-right order.
Constraints
- The total number of leaves and lists combined is at most about 10^6.
- Nesting depth may reach 100,000 or more.
- Leaves may be of any type; only
listinstances are expanded. - The input has no cyclic references.
Examples
Example 1
Input: unnest_list([1, [2, 3], [[4]], 5])
Output: [1, 2, 3, 4, 5]
Example 2
Input: unnest_list([])
Output: []
Example 3
Input: unnest_list([1, [2, [3]]])
Output: [1, 2, 3]
Hints
Hint 1
Think about which value must be handled first: the leftmost one. How can a stack be arranged so that the leftmost pending item is always on top?
Hint 2
When you pop a list, its children should be processed next, before anything that came after that list. Push the children onto the stack so that the first child ends up on top.
Hint 3
Use an isinstance check against list only, so tuples, strings and dicts stay intact, and avoid truthiness checks so values like 0, None and empty strings are kept.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Recursion would be the obvious way to walk a nested structure, but deep nesting would overflow Python's call stack. Instead, keep an explicit stack of items that still need processing, so depth is limited only by heap memory.
- Put all top-level elements on the stack in reverse order, so the leftmost element is on top.
- Repeatedly pop an item.
- If it is a
list, push its children in reverse order. They now sit on top and will be handled, left to right, before any of the list's later siblings. - Otherwise, append it to the result.
- If it is a
- When the stack is empty, return the result.
Only isinstance(x, list) is used to decide whether to expand, so strings, tuples, dicts, None and other falsy values are treated as ordinary leaves and preserved.
Why it is correct
Invariant: reading the stack from top to bottom, preceded by the values already emitted, always gives the correct flattening of the input.
- Initially, the stack top to bottom is
items[0], items[1], ..., so the invariant holds. - Popping a leaf: it is the next value in order, so appending it keeps the invariant.
- Popping a list: replacing it on the stack with its children (first child on top) is exactly what flattening that list in place means.
Each pop either permanently emits a leaf or replaces a list with its contents. Because the input has no cycles, every list is expanded once, so the loop terminates. The input is only read, never mutated.
Complexity
- Time: O(N + L), where N is the number of leaves and L is the number of lists, since each element is pushed and popped once.
- Space: O(N + L) for the stack and result in the worst case. No recursion frames are used.
Reference solution
from typing import List
def unnest_list(items: List[object]) -> List[object]:
result = []
# Reverse so the leftmost element sits on top of the stack.
stack = list(reversed(items))
while stack:
current = stack.pop()
if isinstance(current, list):
# Children take the place of the list, keeping left-to-right order.
stack.extend(reversed(current))
else:
result.append(current)
return result