A "nested list" is a list that contains other lists inside it, sometimes several levels deep — something like [1, [2, 3, [4, 5]], 6]. Flattening means turning that into one flat sequence: [1, 2, 3, 4, 5, 6]. This comes up constantly when you're working with JSON-like data, parsing tree structures, or combining results from multiple sources.

Because the nesting can go arbitrarily deep and unevenly (some branches nested further than others), a loop alone can't handle it cleanly — recursion is the natural fit: whenever an item is itself a list, flatten it the same way, and glue the results together.

Program to Flatten a Nested List (Any Depth) in Python

def flatten(nested_list):
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten(item))   # recurse into the sub-list
        else:
            result.append(item)
    return result


data = [1, [2, 3, [4, 5, [6]]], 7, [8, 9]]
print(f"Original: {data}")
print(f"Flattened: {flatten(data)}")

Output:

Original: [1, [2, 3, [4, 5, [6]]], 7, [8, 9]]
Flattened: [1, 2, 3, 4, 5, 6, 7, 8, 9]

The isinstance(item, list) check is the branch point: if the current item is itself a list, we don't just append it — we flatten it first (recursively) and then extend() the result into our running list. That recursive call keeps happening until every item at every depth is a plain, non-list value.

Flattening Only One Level with itertools.chain

If you know your list is only nested exactly one level deep — a list of lists, no deeper — you don't need recursion at all. itertools.chain.from_iterable() handles that case efficiently:

from itertools import chain

one_level = [[1, 2], [3, 4], [5]]
flat = list(chain.from_iterable(one_level))
print(flat)

Output:

[1, 2, 3, 4, 5]

It's worth picking the right tool for the shape of your data: chain.from_iterable is faster and more idiomatic for single-level nesting, but it will raise an error (or silently misbehave) on deeper nesting, where only the recursive version actually works correctly.