PYTHON
Flatten a Nested List into a Single List
Convert a list containing multiple sublists into a single, one-dimensional list using Python's list comprehension, ideal for consolidating hierarchical data.
nested_list = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened_list = [item for sublist in nested_list for item in sublist]
print(flattened_list)
# Expected output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
How it works: This snippet efficiently flattens a list of lists into a single list using a nested list comprehension. It iterates through each `sublist` in `nested_list`, and for each `sublist`, it iterates through its `item`s, collecting all items into a new, flattened list. This is a common pattern for processing simple hierarchical data structures.