Python Practice › List Programs › Program 90
Flatten a nested list
Write a Python program to flatten a nested list.
Input
[0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]
Output
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
Approach
- Add plain items directly and the contents of sub-lists one by one (recursively for deeper nesting).
Solution
def flatten(items): flat = [] for item in items: if isinstance(item, list): flat.extend(flatten(item)) else: flat.append(item) return flat print(flatten([0, 12, [22, 32], 42, 52, [62, 72, 82], [92, 102, 112, 122]]))Output
[0, 12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122]
Line by line
Lines 4-5
A sub-list is flattened by calling the same function on it, so any depth works.
Learn the concept
New to this topic? Read the lesson, then come back.