PYTHON
Flatten a Nested List in Python
Learn how to efficiently flatten a list of lists into a single, one-dimensional list using Python's list comprehensions or the more performant `itertools.chain`.
import itertools
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# Method 1: Using a list comprehension (concise and Pythonic)
flat_list_comp = [item for sublist in nested_list for item in sublist]
print(f"List comprehension: {flat_list_comp}")
# Method 2: Using itertools.chain (more efficient for large lists)
flat_list_itertools = list(itertools.chain.from_iterable(nested_list))
print(f"itertools.chain: {flat_list_itertools}")
How it works: This snippet demonstrates two common and effective ways to flatten a list of lists (a nested list) into a single, one-dimensional list in Python. The list comprehension provides a concise and readable solution, ideal for simpler cases. For larger or more complex nested structures, `itertools.chain.from_iterable` offers a memory-efficient and generally faster approach by creating an iterator that yields elements from each sublist sequentially.