How do you flatten a nested list in Python?
Posted by IreneSm
Last Updated: August 16, 2024
Flattening a nested list in Python involves converting a list that may contain other lists (or sublists) into a single-level list with all the elements. This is a common task in data manipulation and programming. Here are several methods to achieve this:
1. Using List Comprehension
List comprehension provides a concise way to create lists. For flattening a nested list, you can use a recursive approach.
def flatten(nested_list):
    return [item for sublist in nested_list for item in (flatten(sublist) if isinstance(sublist, list) else [sublist])]

# Example usage
nested = [1, [2, [3, 4], 5], 6]
flat_list = flatten(nested)
print(flat_list)  # Output: [1, 2, 3, 4, 5, 6]
2. Using itertools.chain
The itertools module provides the chain function, which can be useful for flattening lists.
import itertools

def flatten(nested_list):
    flat = list(itertools.chain.from_iterable(
        item if isinstance(item, list) else [item] for item in nested_list
    ))
    return flat

# Example usage
nested = [1, [2, 3], 4]
flat_list = flatten(nested)
print(flat_list)  # Output: [1, 2, 3, 4]
3. Using Recursion
A purely recursive approach involves checking if an element is a list and then recursively flattening it.
def flatten(nested_list):
    flat_list = []
    for item in nested_list:
        if isinstance(item, list):
            flat_list.extend(flatten(item))  # Recursively flatten
        else:
            flat_list.append(item)
    return flat_list

# Example usage
nested = [1, [2, [3, 4], 5], 6]
flat_list = flatten(nested)
print(flat_list)  # Output: [1, 2, 3, 4, 5, 6]
4. Using NumPy (For Numerical Data)
If working primarily with numerical data, NumPy provides a straightforward method for flattening arrays.
import numpy as np

nested = [[1, 2, 3], [4, 5], [6]]
flat_array = np.array(nested).flatten()
print(flat_array)  # Output: [1 2 3 4 5 6]
5. Using a Stack
For a non-recursive approach, a stack can be utilized to achieve the same result.
def flatten(nested_list):
    flat_list = []
    stack = list(nested_list)
    while stack:
        item = stack.pop()
        if isinstance(item, list):
            stack.extend(item)
        else:
            flat_list.append(item)
    return flat_list[::-1]  # Reverse to maintain order

# Example usage
nested = [1, [2, [3, 4], 5], 6]
flat_list = flatten(nested)
print(flat_list)  # Output: [1, 2, 3, 4, 5, 6]
Conclusion
Flattening a nested list in Python can be accomplished through various methods, depending on the specific needs and structure of the data. Whether using list comprehensions, recursion, libraries like NumPy, or even iterative methods, understanding these techniques enables efficient data manipulation and processing in Python programming.