The Simplest Way to Flatten a List in Python
A very common task that you probably have faced is to flat a list, let's show this with a toy example:
nested_numbers = [[1, 2], [3, 4], [5, 6]]
Let's suppose you want to iterate over each one of the numbers in the nested list or just produce a flattened list like this:
flattened_numbers = [1, 2, 3, 4, 5, 6]
Although Python doesn't have an explicit built-in to flatten iterables there are simple ways to do this common task.
You could use a double list comprehension to do this:
flattened_numbers = [number for inner_list in nested_numbers for number in inner_list]
However, I think this usually is confusing and I like to keep my list-comprehensions as simple and unnested as possible. That's why I like this approach the best:
We can use the built-in itertools module's chain method
def flatten(nested_list):
return chain.from_iterable(nested_list)
Please be mindful that chain.from_iterable()
produces a generator expression, so you can iterate directly over it do some computation over the lists, for example, let's multiply each number in nested_list
2 times:
>>> [n * 2 for n in flatten(nested_numbers)]
[2, 4, 6, 8, 10, 12]
If what you want is actually to store the flattened list you can just cast it to list
flattened_numbers = list(flatten(nested_list))