datarekha

How do you flatten a nested list in Python, and how does the approach differ for one level deep versus arbitrarily deep nesting?

The short answer

For a single level of nesting, a list comprehension or itertools.chain.from_iterable is idiomatic and O(n). For arbitrary depth, recursion or an explicit stack is required. The right choice depends on whether the structure is known at write time.

How to think about it

How to approach it

The first thing to clarify is depth: “Is this always one level deep, or can nesting be arbitrary?” That question alone shows you think about generality. One-level problems have elegant O(n) idioms. Arbitrary depth requires a recursive generator, and mentioning the stack concern impresses interviewers.

One level deep — two idiomatic options

For [[1, 2], [3, 4], [5]] there are two clean O(n) approaches:

# List comprehension — most readable
nested = [[1, 2, 3], [4, 5], [6]]
flat = [x for sublist in nested for x in sublist]
# [1, 2, 3, 4, 5, 6]

# itertools.chain.from_iterable — lazy, preferred for large data
import itertools
flat = list(itertools.chain.from_iterable(nested))
# [1, 2, 3, 4, 5, 6]

chain.from_iterable is memory-efficient because it streams elements without building intermediate lists.

Arbitrarily deep nesting — recursive generator

A generator-based recursive approach is the cleanest answer for unknown depth. yield from delegates to the recursive call so Python handles the iteration state, and the generator form avoids accumulating intermediate copies at each level:

def flatten(seq):
    for item in seq:
        if isinstance(item, list):
            yield from flatten(item)
        else:
            yield item

Try it yourself

The key insight

The yield from flatten(item) line is doing two things: it recurses into the sublist AND it delegates the generator protocol — so the caller can drive a single iterator across all levels of nesting without ever building an intermediate list. Memory usage is O(depth), not O(total elements).

Learn it properly Lists

Keep practising

All Python questions

Explore further

Skip to content