To flatten a list of lists into a single flat list in Python, there are a few different approaches you can take. Here are a few common methods:
- Using a list comprehension:
flat_list = [item for sublist in nested_list for item in sublist]
This uses nested list comprehensions to iterate over each sublist in the nested list and extract each item, creating a new flat list.
- Using
itertools.chain()
:
from itertools import chain
flat_list = list(chain.from_iterable(nested_list))
The chain.from_iterable()
function takes an iterable of iterables (in this case, the nested list) and returns a single iterable that flattens the input. We convert the result to a list using list()
.
- Using
sum()
with an empty list as the start value:
flat_list = sum(nested_list, [])
The sum()
function concatenates the sublists together, starting with an empty list []
as the initial value.
- Recursive flattening for arbitrarily nested lists:
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
This recursive approach handles lists with arbitrary levels of nesting. It checks if each item is a list and recursively flattens it, otherwise it appends the item to the flat list.
Here's an example usage:
nested_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
flat_list1 = [item for sublist in nested_list for item in sublist]
print(flat_list1)
from itertools import chain
flat_list2 = list(chain.from_iterable(nested_list))
print(flat_list2)
flat_list3 = sum(nested_list, [])
print(flat_list3)
def flatten(nested_list):
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten(item))
else:
flat_list.append(item)
return flat_list
flat_list4 = flatten(nested_list)
print(flat_list4)
All of these approaches will flatten the nested list [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
into the flat list [1, 2, 3, 4, 5, 6, 7, 8, 9]
.
Choose the method that best fits your needs and coding style. The list comprehension and itertools.chain()
methods are concise and efficient for flattening lists with a known depth, while the recursive approach is more flexible and can handle lists with arbitrary levels of nesting.