I have a nested structure like [[1, 2, 3], [4, 5, 6], [7], [8, 9]], and I’d like to turn it into a flat list: [1, 2, 3, 4, 5, 6, 7, 8, 9].
What’s the cleanest way to python flatten list structures like this, especially when I only need to flatten one level?
For one-level nested lists, I always use a simple list comprehension, it’s concise and Pythonic:
flat_list = [item for sublist in nested_list for item in sublist]
This works perfectly for your example and is super readable. I use it often in data preprocessing tasks.
Same here! That comprehension is my go-to. If you’re looking for a more generic or reusable approach, Python’s built-in itertools.chain
is also great:
import itertools
flat_list = list(itertools.chain.from_iterable(nested_list))
It performs well and avoids nesting loops manually.