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`.
Python code
25 linesdef 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
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
- Use `collections.abc.Iterable` to handle tuples or other iterables, not just lists
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.