KatInterview

Unnest Deeply Nested Lists Without Recursion

Stacks & QueuesAuto-graded · 16 test cases
MediumAuto-gradedStacks & Queuesstackiterationnested-lists

Last 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 list count as nested containers. Every other value is a leaf and must be copied to the result unchanged. This includes strings, tuples, dictionaries, numbers, booleans and None.
  • 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 list instances 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.