PYTHON

Flattening Nested Lists in Python (Recursive Approach)

Learn efficient techniques to flatten complex nested lists into a single, one-dimensional list in Python, essential for processing hierarchical data structures from various sources like JSON payloads or user inputs.

def flatten_list_recursive(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten_list_recursive(item))
        else:
            flat_list.append(item)
    return flat_list

# Example 1: Simple nested list
list1 = [1, [2, 3], 4, [5, [6, 7]]]
flattened1 = flatten_list_recursive(list1)
print(f"Original: {list1}
Flattened: {flattened1}")

# Example 2: More complex nesting
list2 = ["a", ["b", ["c", "d"]], ["e", "f", ["g"]], "h"]
flattened2 = flatten_list_recursive(list2)
print(f"Original: {list2}
Flattened: {flattened2}")

# Example 3: Empty lists
list3 = [1, [], [2, []], 3]
flattened3 = flatten_list_recursive(list3)
print(f"Original: {list3}
Flattened: {flattened3}")
How it works: Flattening a nested list converts it into a single, one-dimensional list, which is often necessary when processing data from APIs or user inputs that might contain arbitrary levels of nesting. This snippet provides a recursive function `flatten_list_recursive`. It iterates through the input list; if an element is itself a list, it calls itself with that sublist and extends the result. Otherwise, it appends the element directly. This process continues until all sublists are unpacked and all individual elements are collected into a flat list.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs