Python Program to Flatten Nested List
def flatten(lst): return [item for sublist in lst for item in (flatten(sublist) if isinstance(sublist, list) else [sublist])] which returns a flat list of all elements.Examples
How to Think About It
Algorithm
Code
def flatten(lst): flat_list = [] for item in lst: if isinstance(item, list): flat_list.extend(flatten(item)) else: flat_list.append(item) return flat_list nested_list = [1, [2, [3, 4], 5], 6] print(flatten(nested_list))
Dry Run
Let's trace the nested list [1, [2, [3, 4], 5], 6] through the flatten function.
Start with the full list
Input list: [1, [2, [3, 4], 5], 6]
Check first element
1 is not a list, add 1 to flat_list
Check second element
[2, [3, 4], 5] is a list, call flatten recursively
Inside recursive call
Process [2, [3, 4], 5]: add 2, flatten [3, 4], add 5
Flatten [3, 4]
Add 3 and 4 to flat_list
Return from recursion
Flattened sublist is [2, 3, 4, 5]
Add last element
6 is not a list, add 6 to flat_list
Final flat list
[1, 2, 3, 4, 5, 6]
| Step | Current Item | Action | Flat List So Far |
|---|---|---|---|
| 1 | 1 | Add 1 | [1] |
| 2 | [2, [3, 4], 5] | Recursive flatten | [1, 2, 3, 4, 5] |
| 3 | 6 | Add 6 | [1, 2, 3, 4, 5, 6] |
Why This Works
Step 1: Check each element
The function looks at each item to see if it is a list or a single value using isinstance(item, list).
Step 2: Use recursion for nested lists
If the item is a list, the function calls itself to flatten that smaller list before adding its elements.
Step 3: Collect all elements
All non-list items are added directly to the result list, building a flat list step by step.
Alternative Approaches
def flatten_gen(lst): for item in lst: if isinstance(item, list): yield from flatten_gen(item) else: yield item nested_list = [1, [2, [3, 4], 5], 6] print(list(flatten_gen(nested_list)))
def flatten_iter(lst): stack = lst[::-1] flat_list = [] while stack: item = stack.pop() if isinstance(item, list): stack.extend(item[::-1]) else: flat_list.append(item) return flat_list nested_list = [1, [2, [3, 4], 5], 6] print(flatten_iter(nested_list))
Complexity: O(n) time, O(n) space
Time Complexity
The function visits each element once, so the time grows linearly with the total number of elements including nested ones.
Space Complexity
Extra space is needed to store the flattened list and the recursion call stack, both proportional to the total number of elements.
Which Approach is Fastest?
Recursive and iterative stack methods have similar time complexity; the generator method can save memory but may be slightly slower due to yield overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Recursive | O(n) | O(n) | Simple code, any depth |
| Generator | O(n) | O(n) | Memory efficient, lazy evaluation |
| Iterative Stack | O(n) | O(n) | Avoid recursion limits |