SnippetPython
Flatten a nested list
Flattens a list of lists by one level using a nested list comprehension, with a note on when you actually need recursion instead.
Last updated
Snippetpython
def flatten(nested):
return [item for sub in nested for item in sub]
# flatten([[1, 2], [3], [4, 5]]) -> [1, 2, 3, 4, 5]How it works
This is a nested comprehension read left to right the same way you'd write the equivalent loop: for sub in nested, then for item in sub, appending each item — it's the idiomatic one-liner for flattening exactly one level, and it's faster than sum(nested, []) which builds and discards an intermediate list at every step.
Keeping it to one level is a deliberate scope decision: a function that flattens arbitrarily deep, mixed-depth structures needs recursion and a type check to tell a list apart from a leaf value, which is a different (and slower, less predictable) tool than this one.
Edge cases to know
- →Nested lists deeper than one level stay nested: flatten([[1, [2, 3]], [4]]) returns [1, [2, 3], 4], not a fully flat list — reach for a recursive flattener if your input's depth isn't fixed.
- →Every element of nested must itself be iterable; flatten([1, [2, 3]]) raises a TypeError on the bare 1, since int isn't iterable.
- →Order is preserved and duplicates are kept exactly as they appear — this does no deduplication or sorting.