Mastering Python: How to Flatten Nested Lists Step by Step

By

Introduction

Flattening a list of lists — converting a multidimensional structure like [[1, 2], [3, 4]] into a single flat list [1, 2, 3, 4] — is a common task in Python. Whether you’re processing JSON data, cleaning up matrix operations, or preparing inputs for machine learning models, knowing how to flatten lists efficiently can save you time and headaches. This guide walks you through multiple approaches, from simple loops to advanced functional tools, so you can choose the best method for your specific scenario.

Mastering Python: How to Flatten Nested Lists Step by Step
Source: realpython.com

What You Need

Step-by-Step Guide

Step 1: Flatten with a Nested For Loop

The most straightforward way to flatten a list of lists is by using two for loops: one to iterate over the outer list and one to iterate over each inner list. You collect every element into a new list.

nested = [[1, 2], [3, 4], [5]]
flat = []
for sublist in nested:
    for item in sublist:
        flat.append(item)
print(flat)  # [1, 2, 3, 4, 5]

Why it works: The outer loop grabs each inner list; the inner loop unpacks its elements. This method is explicit and works with any number of sublists. However, it becomes verbose if you need to flatten deeply nested structures (lists within lists within lists).

Step 2: Use List Comprehension

Python’s list comprehension offers a concise, Pythonic alternative. The pattern [item for sublist in nested for item in sublist] does the same job in one line.

nested = [[1, 2], [3, 4], [5]]
flat = [item for sublist in nested for item in sublist]
print(flat)

Tip: The order of for clauses in a comprehension mirrors the order in a nested loop — first the outer loop, then the inner loop. This is a common point of confusion.

Step 3: Leverage itertools.chain

The itertools module provides chain.from_iterable(), which is optimized for flattening. It returns an iterator; wrap it in list() to get the flat list.

from itertools import chain
nested = [[1, 2], [3, 4], [5]]
flat = list(chain.from_iterable(nested))
print(flat)

Advantage: chain.from_iterable() is memory‑efficient because it yields elements one by one instead of building an intermediate list. Use this when working with huge datasets.

Step 4: Flatten Arbitrarily Deep Nesting Recursively

If your data has variable or unknown depth (e.g., [[1, [2, 3]], 4] or a tree structure), a simple loop or comprehension won’t suffice. You need a recursive function that checks whether an element is a list and, if so, flattens it further.

def deep_flatten(nested):
    result = []
    for item in nested:
        if isinstance(item, list):
            result.extend(deep_flatten(item))
        else:
            result.append(item)
    return result

nested = [1, [2, [3, 4]], 5]
print(deep_flatten(nested))  # [1, 2, 3, 4, 5]

Important: This recursive approach works for mixed types as long as the non‑list items are scalar values. For strings, isinstance(item, list) will not treat them as iterables (which is usually what you want).

Mastering Python: How to Flatten Nested Lists Step by Step
Source: realpython.com

Step 5: Use a Library like more-itertools

For a battle‑tested solution that handles edge cases (strings, generators, etc.), consider the more-itertools package. It provides collapse() which flattens any iterable depth‑first.

from more_itertools import collapse
nested = [1, [2, [3, 4]], 5]
flat = list(collapse(nested))
print(flat)  # [1, 2, 3, 4, 5]

Why use it: collapse automatically handles strings as atomic elements (doesn’t split them into characters), respects custom base types, and is highly tested.

Tips for Flattening Lists in Python

Now you have a toolkit of five methods to flatten lists in Python. Each has its strengths — from simple loops to robust library functions. Pick the one that fits the complexity of your data and the clarity you need for your code.

Related Articles

Recommended

Discover More

7 Critical Insights for Analyzing Hugging Face Arm64 ReadinessNavigating the AI Wave: Insights from ThoughtWorks' Technology Radar Volume 34Rethinking Efficiency: How AI's 'Bug-Free' Promise Can Erode Team Trust and CultureExploring NVIDIA's Open Ising Models for Quantum Computing Challenges8 Critical Facts About the DarkSword iOS Exploit Chain You Need to Know