PYTHON
Flatten a Nested List Recursively
Learn to flatten a nested list in Python into a single-level list using a recursive function. Useful for processing complex, hierarchical data structures received from APIs or files.
def flatten_list(nested_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:
nested_data = [1, [2, 3], [4, [5, 6]], 7]
flattened_data = flatten_list(nested_data)
print(f"Nested list: {nested_data}")
print(f"Flattened list: {flattened_data}")
How it works: This snippet provides a recursive function `flatten_list` that efficiently converts a list containing nested sublists into a single-dimensional list. It iterates through each item; if an item is a list, it recursively calls itself to flatten that sublist and extends the result. Otherwise, it appends the item directly. This is particularly useful when processing data with varying levels of nesting, ensuring a consistent structure for further operations.