Skip to content
Explain to Dev
Explain to Dev

Empowering developers with the knowledge to build, create, and innovate in the software world.

  • Home
  • About
  • Java
  • Python
  • PHP
  • .NET
  • Node.js
  • SQL
  • Privacy Policy
Explain to Dev

Empowering developers with the knowledge to build, create, and innovate in the software world.

How to Flatten a Nested List of Arbitrary Depth in Python

etd_admin, March 23, 2025March 23, 2025

Flattening a nested list of arbitrary depth in Python means converting a deeply nested list into a single-level list while preserving the order of elements. There are multiple ways to achieve this, including recursion and iteration.

Using Recursion

Recursion is a straightforward way to flatten a nested list of arbitrary depth in Python. We define a function that checks each element—if it’s a list, we recursively process it; otherwise, we add it to the result.

def flatten_list(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten_list(item))  # Recursive call for nested lists
        else:
            flat_list.append(item)  # Append non-list elements directly
    return flat_list

# Test case
nested = [1, [2, [3, 4], 5], [6, 7, [8, [9, 10]]]]
print(flatten_list(nested))

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This method efficiently flattens a nested list of arbitrary depth in Python by breaking down the problem into smaller pieces.

Using a Stack (Iteration)

Recursion can hit Python’s recursion depth limit for very deep lists. An iterative approach using a stack avoids this issue.

def flatten_list_iterative(nested_list):
    stack = nested_list[::-1]  # Reverse to process from left to right
    flat_list = []
    
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(item[::-1])  # Reverse before adding to maintain order
        else:
            flat_list.append(item)

    return flat_list

# Test case
nested = [1, [2, [3, 4], 5], [6, 7, [8, [9, 10]]]]
print(flatten_list_iterative(nested))

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Using yield and Generators

A generator function allows lazy evaluation, which is useful for large nested lists.

def flatten_list_generator(nested_list):
    for item in nested_list:
        if isinstance(item, list):
            yield from flatten_list_generator(item)  # Recursively yield items
        else:
            yield item

# Test case
nested = [1, [2, [3, 4], 5], [6, 7, [8, [9, 10]]]]
print(list(flatten_list_generator(nested)))

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

This method is an efficient way to flatten a nested list of arbitrary depth in Python without building an intermediate list in memory.

Python ListsPython

Post navigation

Previous post
Next post
©2025 Explain to Dev | WordPress Theme by SuperbThemes