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.
Python code
12 linesdef 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
[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
- Use a stack-based iterative approach to avoid recursion depth limits
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.