Flattening a list of lists into a single flat list can be achieved using various techniques in Python. Here are the most common methods:
1. Using List Comprehension
This is one of the simplest and most Pythonic methods to flatten a list of lists.
# List of lists
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
# Flatten the list using list comprehension
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2. Using the itertools.chain
Function
The itertools.chain
function is a fast and efficient way to flatten a list of lists.
from itertools import chain
# List of lists
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
# Flatten the list using itertools.chain
flat_list = list(chain.from_iterable(nested_list))
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
3. Using sum()
with an Empty List
The sum()
function can concatenate lists when used with an empty list as the starting point.
# List of lists
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
# Flatten the list using sum()
flat_list = sum(nested_list, [])
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Note: This method is less efficient for large lists as it creates intermediate lists during the summation.
4. Using a Nested Loop
This is a more verbose but straightforward approach.
# List of lists
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
# Flatten the list using a nested loop
flat_list = []
for sublist in nested_list:
for item in sublist:
flat_list.append(item)
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
5. Using numpy
(if working with numerical data)
If you're working with numerical data, numpy
provides an efficient way to flatten a list of lists.
import numpy as np
# List of lists
nested_list = [
[1, 2, 3],
[4, 5, 6],
[7],
[8, 9]
]
# Flatten the list using numpy
flat_list = np.concatenate(nested_list).tolist()
print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Which Method Should You Use?
-
Small/Medium Lists: Use list comprehension or
itertools.chain
for clarity and performance. -
Large Lists: Use
itertools.chain
, as it is optimized for iterables. -
Numerical Data: Use
numpy
if you already rely onnumpy
for other tasks. - Explicit Loops: Use a nested loop if readability is a priority and the list comprehension is too complex for others to understand.
Top comments (0)