PYTHON
Flatten Nested Lists with List Comprehension
Transform a list of lists into a single, flat list using a concise Python list comprehension, simplifying data processing for complex nested structures in web development.
# Example 1: Flattening a simple list of lists
nested_list_1 = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list_1 = [item for sublist in nested_list_1 for item in sublist]
print(f"Flattened list 1: {flattened_list_1}")
# Expected: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Example 2: Flattening with a condition (e.g., only even numbers)
nested_list_2 = [[10, 11, 12], [13, 14], [15, 16, 17]]
flattened_evens = [item for sublist in nested_list_2 for item in sublist if item % 2 == 0]
print(f"Flattened even numbers: {flattened_evens}")
# Expected: [10, 12, 14, 16]
# Example 3: Flattening a list of tuples or other iterables
list_of_tuples = [('a', 'b'), ('c', 'd', 'e'), ('f',)]
flattened_tuples = [char for tpl in list_of_tuples for char in tpl]
print(f"Flattened tuples: {flattened_tuples}")
# Expected: ['a', 'b', 'c', 'd', 'e', 'f']
How it works: List comprehensions provide a concise way to create lists. To flatten a nested list (a list of lists) into a single list, you can use a nested list comprehension. The syntax `[item for sublist in nested_list for item in sublist]` iterates through each `sublist` in the `nested_list`, and then for each `item` within that `sublist`, it adds the `item` to the new flattened list. This elegant one-liner is highly readable and efficient for transforming hierarchical data.