PYTHON
Flatten a List of Lists
Learn efficient Python methods to flatten a nested list of lists into a single, one-dimensional list, useful for consolidating data structures from various sources.
import itertools
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# Method 1: Using list comprehension (suitable for fixed depth or simple cases)
def flatten_list_comprehension(nested):
return [item for sublist in nested for item in sublist]
flat_list_lc = flatten_list_comprehension(nested_list)
print(f"Flattened (List Comprehension): {flat_list_lc}")
# Method 2: Using itertools.chain.from_iterable (more efficient for large lists)
def flatten_itertools(nested):
return list(itertools.chain.from_iterable(nested))
flat_list_itertools = flatten_itertools(nested_list)
print(f"Flattened (itertools.chain): {flat_list_itertools}")
# Expected Output:
# Flattened (List Comprehension): [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Flattened (itertools.chain): [1, 2, 3, 4, 5, 6, 7, 8, 9]
How it works: Flattening a list of lists transforms a nested structure into a single, one-dimensional list. This snippet presents two common and efficient methods in Python. The first uses a nested list comprehension, which is concise and readable for scenarios where the nesting level is known and relatively shallow. The second method utilizes `itertools.chain.from_iterable`, which is generally more memory-efficient and faster for very large or deeply nested lists because it creates an iterator that yields elements one by one, avoiding the creation of intermediate lists.