0
0
PythonHow-ToBeginner · 3 min read

How to Flatten Nested List in Python: Simple Methods Explained

To flatten a nested list in Python, you can use a simple for loop or a recursive function to extract all inner elements into a single list. Using list comprehensions or the itertools.chain method also helps to flatten lists efficiently.
📐

Syntax

Here are common ways to flatten a nested list:

  • Using a loop: Iterate through each sublist and add elements to a new list.
  • Using list comprehension: A concise way to flatten one level of nesting.
  • Using recursion: To flatten lists nested at multiple levels.
python
flat_list = []
for sublist in nested_list:
    for item in sublist:
        flat_list.append(item)

# Or using list comprehension
flat_list = [item for sublist in nested_list for item in sublist]

# Recursive flatten function
def flatten(lst):
    result = []
    for el in lst:
        if isinstance(el, list):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result
💻

Example

This example shows how to flatten a nested list with multiple levels using a recursive function.

python
def flatten(lst):
    result = []
    for el in lst:
        if isinstance(el, list):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

nested_list = [1, [2, [3, 4], 5], 6]
flat = flatten(nested_list)
print(flat)
Output
[1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

One common mistake is trying to flatten deeply nested lists with a simple list comprehension, which only works for one level of nesting. Another is modifying the list while iterating, which can cause errors or unexpected results.

Also, using sum(nested_list, []) to flatten is discouraged because it is inefficient for large lists.

python
nested_list = [1, [2, [3, 4], 5], 6]

# Incorrect: only flattens one level
flat_wrong = [item for sublist in nested_list for item in (sublist if isinstance(sublist, list) else [sublist])]
print(flat_wrong)  # Output: [1, 2, [3, 4], 5, 6]

# Correct: use recursion to flatten all levels
def flatten(lst):
    result = []
    for el in lst:
        if isinstance(el, list):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

flat_correct = flatten(nested_list)
print(flat_correct)  # Output: [1, 2, 3, 4, 5, 6]
Output
[1, 2, [3, 4], 5, 6] [1, 2, 3, 4, 5, 6]
📊

Quick Reference

  • One-level flatten: Use list comprehension [item for sublist in nested_list for item in sublist]
  • Multi-level flatten: Use recursive function to handle any depth
  • Avoid: Using sum() for flattening large lists

Key Takeaways

Use list comprehension to flatten nested lists with one level of nesting.
Use a recursive function to flatten lists nested at multiple levels.
Avoid modifying lists while iterating to prevent errors.
Do not use sum() to flatten lists as it is inefficient for large data.
Check element types with isinstance() to handle nested lists correctly.