Flatten a Nested List
Flatten a Nested List is a reusable Python snippet. Multiple methods to flatten nested lists, from simple to deep recursion. The full implementation: # Simple: one level deep nested = [[1, 2], [3, 4], [5, 6]] flat = [item for sublist in nested for item in sublist] # [1, 2, 3, 4, 5, 6] # Using itertools.chain from itertools import chain flat = list(chain.from_iterable(nested)) # Deep flatten (recursive) def deep_flatten(lst): result = [] for item in lst: if isinstance(item, list): result.extend(deep_flatten(item)) else: result.append(item) return result deep_flatten([1, [2, [3, 4]], 5]) # [1, 2, 3, 4, 5] It belongs to the Itertools Module area of the standard library. This snippet uses only the Python standard library with no third-party dependencies, so it runs on any modern Python 3 interpreter. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.