PYTHON

Flatten a Nested List of Lists in Python

Explore various Pythonic ways to flatten a list containing sublists into a single, one-dimensional list, useful for processing structured data from APIs or databases.

import itertools

nested_list = [
    [1, 2, 3],
    [4, 5],
    [6, [7, 8]], # Note: This example does not handle arbitrarily deep nesting without recursion
    [9]
]

# Method 1: Using a nested list comprehension (for lists of lists)
flat_list_comp = [item for sublist in nested_list[:3] for item in sublist]
# Result: [1, 2, 3, 4, 5, 6, [7, 8]] - Note: The [7,8] is still a list

# Method 2: Using itertools.chain.from_iterable (efficient for iterables)
# This is generally preferred for performance and readability with simple nesting.
flat_list_chain = list(itertools.chain.from_iterable(nested_list[:3]))
# Result: [1, 2, 3, 4, 5, 6, [7, 8]]

# Method 3: Handling deeper (but still known depth) nesting with multiple comprehensions
deeply_nested_list = [
    [1, 2],
    [3, [4, 5]],
    [6]
]

# Flattens one level at a time
semi_flat = [item for sublist in deeply_nested_list for item in sublist]
# semi_flat: [1, 2, 3, [4, 5], 6]

# To fully flatten arbitrarily deep nesting, a recursive function is needed
def flatten_recursive(lst):
    flat = []
    for item in lst:
        if isinstance(item, list):
            flat.extend(flatten_recursive(item))
        else:
            flat.append(item)
    return flat

arbitrarily_nested = [1, [2, 3], [4, [5, 6]], 7]
fully_flat = flatten_recursive(arbitrarily_nested)
# Result: [1, 2, 3, 4, 5, 6, 7]
How it works: Flattening a nested list means converting a list of lists into a single, one-dimensional list. For simple one-level nesting, list comprehensions or `itertools.chain.from_iterable` offer concise and efficient solutions. `itertools.chain.from_iterable` is particularly useful for combining iterables and is often more memory-efficient for large datasets. For arbitrarily deep nesting (where lists can contain other lists to any depth), a recursive function is typically required. This function checks each item: if it's a list, it recursively flattens it; otherwise, it appends the item directly.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs