0
0
PythonProgramBeginner · 2 min read

Python Program to Flatten Nested List

You can flatten a nested list in Python using a recursive function like 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

Input[1, 2, 3]
Output[1, 2, 3]
Input[1, [2, 3], 4]
Output[1, 2, 3, 4]
Input[[1, [2, [3, 4]], 5], 6]
Output[1, 2, 3, 4, 5, 6]
🧠

How to Think About It

To flatten a nested list, think about checking each item: if it is a list, break it down further by flattening it; if it is not a list, keep it as is. Repeat this until all nested lists are opened and all elements are collected in one simple list.
📐

Algorithm

1
Take the input list.
2
For each element in the list, check if it is a list itself.
3
If it is a list, call the flatten function on it to break it down further.
4
If it is not a list, add the element directly to the result.
5
Combine all results into one flat list and return it.
💻

Code

python
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))
Output
[1, 2, 3, 4, 5, 6]
🔍

Dry Run

Let's trace the nested list [1, [2, [3, 4], 5], 6] through the flatten function.

1

Start with the full list

Input list: [1, [2, [3, 4], 5], 6]

2

Check first element

1 is not a list, add 1 to flat_list

3

Check second element

[2, [3, 4], 5] is a list, call flatten recursively

4

Inside recursive call

Process [2, [3, 4], 5]: add 2, flatten [3, 4], add 5

5

Flatten [3, 4]

Add 3 and 4 to flat_list

6

Return from recursion

Flattened sublist is [2, 3, 4, 5]

7

Add last element

6 is not a list, add 6 to flat_list

8

Final flat list

[1, 2, 3, 4, 5, 6]

StepCurrent ItemActionFlat List So Far
11Add 1[1]
2[2, [3, 4], 5]Recursive flatten[1, 2, 3, 4, 5]
36Add 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

Using a generator with yield
python
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)))
This method uses a generator to yield elements one by one, which can be more memory efficient for large lists.
Using iterative stack approach
python
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))
This method avoids recursion by using a stack to process elements, useful to prevent recursion limits.

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.

ApproachTimeSpaceBest For
RecursiveO(n)O(n)Simple code, any depth
GeneratorO(n)O(n)Memory efficient, lazy evaluation
Iterative StackO(n)O(n)Avoid recursion limits
💡
Use recursion to handle any depth of nested lists easily.
⚠️
Beginners often forget to check if an element is a list before flattening, causing errors or incomplete flattening.