Flatten a Nested List in Python (Recursive Generator)

Recursively flatten arbitrarily nested lists into a single-level list using both a function and a generator with `yield from`.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 14 views 0 copies

Python code

25 lines
Python 3.9+
def flatten(nested_list):
    """Recursively flatten a nested list into a single-level list."""
    result = []
    for item in nested_list:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result


def flatten_generator(nested_list):
    """Generator version that yields items one at a time."""
    for item in nested_list:
        if isinstance(item, list):
            yield from flatten_generator(item)
        else:
            yield item


if __name__ == "__main__":
    data = [1, [2, [3, 4], 5], [6, 7], 8]

    print("Flattened list:", flatten(data))
    print("Generator result:", list(flatten_generator(data)))

Output

stdout
Flattened list: [1, 2, 3, 4, 5, 6, 7, 8]
Generator result: [1, 2, 3, 4, 5, 6, 7, 8]

How it works

The flatten function checks each item with isinstance(item, list). If it's a list, it recursively flattens that sublist and extends the result; otherwise it appends the item. The generator version flatten_generator uses yield from, which delegates iteration to the recursive call, making it memory-efficient for large or deeply nested inputs. The base case is when an item is not a list, at which point it yields the item directly. Both versions preserve the original order of non-list elements.

Common mistakes

  • Using `append` instead of `extend` on the recursive call, which nests sublists instead of flattening
  • Forgetting the `isinstance` check, causing TypeError on non-list iterables
  • Mixing `yield` and `return` incorrectly in the generator, which can stop iteration early

Variations

  1. Use `collections.abc.Iterable` to handle tuples or other iterables, not just lists
  2. Write an iterative version using a stack to avoid recursion depth limits

Real-world use cases

  • Flattening API responses that contain nested JSON arrays before processing.
  • Converting a tree-like structure (e.g., org charts) into a flat list of node IDs.
  • Generating a flat sequence of all files from a nested directory tree in a build script.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.