How to Flatten a Deeply Nested List in Python Recursively

A recursive function that flattens arbitrarily deep nested lists into a single flat list using isinstance checks.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 13 views 0 copies

Python code

12 lines
Python 3.9+
def flatten(nested_list):
    if not nested_list:
        return []
    if isinstance(nested_list[0], list):
        return flatten(nested_list[0]) + flatten(nested_list[1:])
    return [nested_list[0]] + flatten(nested_list[1:])


if __name__ == "__main__":
    data = [1, [2, [3, [4, [5]]]], [6, [7, [8, [9]]]], 10]
    result = flatten(data)
    print(result)

Output

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

How it works

This function recursively processes the first element of the list. If it is a list, we flatten it and recursively flatten the rest. If not, we keep the element as is and continue with the tail. The base case returns an empty list when the input is empty, which allows the recursion to terminate. This approach works for arbitrarily deep nesting without requiring an external library.

Common mistakes

  • Forgetting to handle empty lists inside the nesting, causing recursion to hit an index error
  • Using a shallow copy or modifying the original list in place
  • Assuming only integers are present instead of using isinstance for general types

Variations

  1. Use a stack-based iterative approach to avoid recursion depth limits
  2. Use itertools.chain.from_iterable in a loop for semi-nested structures

Real-world use cases

  • Parsing nested JSON payloads where fields are deeply embedded and needed as a flat list.
  • Converting tree structures (e.g., category hierarchies) into a flat list for database inserts.
  • Processing configuration files with arbitrary nesting levels to extract all scalar values.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.