PYTHON
Flatten a Nested List in Python Efficiently
Learn multiple Python methods to flatten a list of lists (or any nested iterable) into a single, one-dimensional list, improving data processing and simplifying subsequent operations.
import itertools
# Example nested list
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
# Method 1: Using a list comprehension (common and Pythonic)
flattened_comprehension = [item for sublist in nested_list for item in sublist]
print(f"Flattened with comprehension: {flattened_comprehension}")
# Method 2: Using sum() (less efficient for large lists, but concise)
# Only works for lists of lists where sublists contain numbers or similar concatenable types.
flattened_sum = sum(nested_list, [])
print(f"Flattened with sum(): {flattened_sum}")
# Method 3: Using itertools.chain.from_iterable (most efficient for large lists)
flattened_itertools = list(itertools.chain.from_iterable(nested_list))
print(f"Flattened with itertools.chain: {flattened_itertools}")
# Example with mixed data types or empty sublists
mixed_nested_list = [['a', 'b'], [], ['c'], [1, 2, 'd']]
flattened_mixed = [item for sublist in mixed_nested_list for item in sublist]
print(f"Flattened mixed list: {flattened_mixed}")
How it works: This snippet illustrates three common and efficient ways to flatten a nested list (a list containing other lists) into a single, one-dimensional list in Python. The list comprehension method is highly Pythonic and readable for most use cases. The `sum()` function, while concise, can be less efficient for very large lists due to repeated list concatenation. For optimal performance with large datasets or when dealing with iterables beyond just lists, `itertools.chain.from_iterable` is the most recommended approach. Flattening lists is a frequent task in web development for processing structured data from APIs, databases, or user input, allowing for easier iteration and manipulation of all elements.