PYTHON
Flatten a Nested List of Arbitrary Depth
Efficiently flatten a Python list containing sublists or even deeper nested structures into a single, one-dimensional list, essential for processing complex data arrays.
def flatten_list(nested_list):
"""Recursively flattens a nested list into a single list."""
flat_list = []
for item in nested_list:
if isinstance(item, list):
flat_list.extend(flatten_list(item))
else:
flat_list.append(item)
return flat_list
# Example usage:
complex_list = [1, [2, 3], [4, [5, 6, [7]]], 8]
flattened = flatten_list(complex_list)
print("Original nested list:", complex_list)
print("Flattened list:", flattened)
# Using a more concise generator expression for simpler cases (single depth)
list_of_lists = [[1, 2], [3, 4], [5]]
flattened_gen = [item for sublist in list_of_lists for item in sublist]
print("Flattened with generator (single depth):", flattened_gen)
How it works: This code provides a recursive function `flatten_list` to convert a list with arbitrary levels of nesting into a single flat list. It iterates through each item; if an item is a list, it recursively calls itself and extends the result. Otherwise, it appends the item directly. A simpler list comprehension example is also provided for flattening lists that are only one level deep.