Flattening Nested Arrays in Python

Nested arrays are often cumbersome to deal with, especially if they are deeply nested. Here’s a Python function using recursion to flatten any nested list.

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

# Example
nested_list = [1, [2, [3, 4]], 5]
print(flatten_list(nested_list))  # Output: [1, 2, 3, 4, 5]

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top