Skip to content
UniCircle
MediumCodingRecursion and generators

Flatten a nested list and report its depth

Question PY-REC-103

You are given a nested list of integers written as a Python literal, such as [1, [2, [3, 4]], [], 5]. Print:

  1. the maximum nesting depth: a list with no inner lists has depth 1, so [] and [1, 2] have depth 1, and [[ ]] has depth 2;
  2. all the integers in left-to-right order, flattened onto one line.

Use a recursive generator (yield from).

Constraints

  • Depth ≤ 60
  • At most 5000 integers; each fits in a 32-bit int.

Input and output

Input
One line: a valid Python list literal containing only integers and lists.
Output
Line 1: the depth. Line 2: the integers separated by spaces (an empty line if there are none).

Examples

Input 1

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

Output

3
1 2 3 4 5

The deepest list, [3, 4], is 3 levels down.

Input 2

[[], [[]]]

Output

3

There are no integers, so line 2 is empty; [[]] inside the outer list gives depth 3.

Show hints
  • ast.literal_eval safely turns the text into a list. Never use eval on input.
  • The depth of a list is 1 + the largest depth among its sub-lists (0 if it has none).
Show the explanation
Python
def flatten(x):
    for item in x:
        if isinstance(item, list):
            yield from flatten(item)     # delegate to the sub-generator
        else:
            yield item

def depth(x):
    return 1 + max((depth(i) for i in x if isinstance(i, list)), default=0)

Key ideas

  • Parsing safely: ast.literal_eval accepts only literals (numbers, strings, lists, dicts and so on). eval would run any code in the input, which is a classic security mistake.
  • `yield from` passes along every value from the inner generator. The flattened list is produced lazily, one value at a time, with no intermediate lists. list(flatten(data)) collects it when you need it.
  • `max(..., default=0)` handles lists that contain no sub-lists, including [].
  • Recursion depth: CPython's default limit is about 1000 frames (sys.getrecursionlimit()), so very deep input would need an explicit stack. That makes a good follow-up: rewrite flatten with a stack of iterators.

The time is O(total elements). The extra space is O(depth) for the recursion.

Original UniCircle question. Last reviewed 22 Oct 2026.