Back to Home
Python

⭐ How to Flatten Lists in Python: A Complete, Beginner‑Friendly Guide

Olatunji Azeez
May 11, 2026
0 views
⭐ How to Flatten Lists in Python: A Complete, Beginner‑Friendly Guide

Working with nested lists is common in Python, especially when dealing with matrices, JSON data, or grouped results. But many operations — from data analysis to machine learning — require your data in a single, one‑dimensional list.
That’s where flattening comes in.

This guide walks you through every practical way to flatten lists in Python, from simple loops to advanced tools like itertools, reduce(), recursion, and NumPy. You’ll also see which method performs best and when to use each one.

🔍 What Does “Flattening a List” Mean?

Flattening means converting a structure like this:

python

[
    [9, 3, 8, 3],
    [4, 5, 2, 8],
    [6, 4, 3, 1],
    [1, 0, 4, 5]
]

into this:

python

[9, 3, 8, 3, 4, 5, 2, 8, 6, 4, 3, 1, 1, 0, 4, 5]

You’re essentially taking all inner lists and merging their elements into one continuous list.

🧩 1. Flattening With a Simple for Loop

The most intuitive approach is to loop through each sublist and extend a new list.

Using .extend()

python

def flatten_extend(matrix):
    flat = []
    for row in matrix:
        flat.extend(row)
    return flat

.extend() adds all items from each sublist into the final list.
It’s clean, readable, and surprisingly fast.

Using += (augmented concatenation)

python

def flatten_concat(matrix):
    flat = []
    for row in matrix:
        flat += row
    return flat

This works the same way but is slightly less explicit.
Both methods produce identical results.

🧩 2. Flattening With a List Comprehension

Python developers love list comprehensions because they’re compact and expressive.

python

def flatten_comprehension(matrix):
    return [item for row in matrix for item in row]

This one‑liner loops through each row, then each item, and builds a new list.
It’s elegant and Pythonic.

🧩 3. Using Standard Library Tools

Python’s standard library includes several utilities that can flatten lists without writing loops manually.

🔗 itertools.chain()

chain.from_iterable() is designed to treat multiple iterables as one continuous sequence.

python

from itertools import chain

def flatten_chain(matrix):
    return list(chain.from_iterable(matrix))

This is clean and memory‑efficient because it works lazily.

🔁 functools.reduce()

reduce() repeatedly applies a function to accumulate results.

Using a lambda:

python

from functools import reduce

def flatten_reduce(matrix):
    return reduce(lambda x, y: x + y, matrix, [])

Using operator functions:

python

from operator import add, concat, iconcat

reduce(add, matrix, [])
reduce(concat, matrix, [])
reduce(iconcat, matrix, [])

iconcat is the fastest of the three because it mutates the list in place.

➕ Using sum()

Although unconventional, sum() can concatenate lists:

python

def flatten_sum(matrix):
    return sum(matrix, [])

It works — but it’s slow and not recommended for large datasets.

🧩 4. Flattening Deeply Nested Lists

The previous methods assume only one level of nesting.
But real‑world data (JSON, directory trees, API responses) often contains arbitrarily deep nesting.

Here are two ways to handle that.

🔁 Recursive Flattening

python

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

This walks through every level until all values are extracted.

⚠️ Deep nesting may hit Python’s recursion limit.

🧱 Iterative Flattening With a Stack

This avoids recursion entirely:

python

def flatten_iterative(nested):
    flat = []
    stack = [iter(nested)]

    while stack:
        for item in stack[-1]:
            if isinstance(item, list):
                stack.append(iter(item))
                break
            flat.append(item)
        else:
            stack.pop()

    return flat

This version can handle extremely deep structures without errors.

🚀 5. Performance Comparison

When flattening a large 1000×1000 matrix, here’s how the methods typically rank (fastest → slowest):

Rank

Method

Why

🥇 1

+= concatenation

In‑place mutation

🥈 2

.extend()

Also in‑place

🥉 3

reduce(iconcat)

In‑place concatenation

4

itertools.chain()

Efficient but requires list()

5

List comprehension

Two nested loops

🚫 Slowest

reduce(add/concat) and sum()

Creates many intermediate lists

Conclusion:
If performance matters, use .extend() or +=.

📊 6. Flattening Arrays in NumPy

If you’re working in data science, you’ll often use NumPy arrays instead of Python lists.

NumPy provides a built‑in method:

python

import numpy as np

matrix = np.array([
    [9, 3, 8, 3],
    [4, 5, 2, 8],
    [6, 4, 3, 1],
    [1, 0, 4, 5]
])

matrix.flatten()

This returns a 1‑D NumPy array, optimized for numerical operations.

🎯 Final Thoughts

Flattening lists is a common task in Python, and you now have a full toolbox of techniques:

  • Use loops (extend or +=) for speed and clarity.

  • Use list comprehensions for concise, readable code.

  • Use itertools.chain() for memory‑efficient flattening.

  • Use recursion or stacks for deeply nested structures.

  • Use NumPy when working with scientific data.

With these tools, you can handle any nested data structure Python throws at you.

Share this article

Loading comments...