Mastering List Flattening in Python: A Step-by-Step Guide

By

What You Need

Step-by-Step Instructions

Step 1: Prepare Your Nested List

Start with a list of lists, like a matrix with rows and columns. For example:

Mastering List Flattening in Python: A Step-by-Step Guide
Source: realpython.com
matrix = [
    [9, 3, 8, 3],
    [4, 5, 2, 8],
    [6, 4, 3, 1],
    [1, 0, 4, 5]
]

This matrix has four nested lists (rows), each with four numbers. Your goal is to flatten it into a one‑dimensional list: [9, 3, 8, 3, 4, 5, 2, 8, 6, 4, 3, 1, 1, 0, 4, 5].

Step 2: Flatten Using a for Loop and .extend()

The most straightforward method. Create an empty list, then loop through each sublist and extend your result list with its elements.

  1. Initialize: flattened = []
  2. Loop: for sublist in matrix: flattened.extend(sublist)
  3. Print or use flattened.

That's it! .extend() adds every item from the sublist, one by one. You can also use the += operator: flattened += sublist.

Step 3: Flatten Using a List Comprehension

A concise one‑liner. The comprehension iterates over each sublist and then over each element, collecting them into a new list.

flattened = [item for sublist in matrix for item in sublist]

This works exactly like the for loop but in a single expression. Performance is similar; choose based on readability.

Step 4: Flatten Using itertools.chain()

Python's itertools module provides chain() to combine multiple iterables. Use the unpacking operator * to pass the sublists.

import itertools
flattened = list(itertools.chain(*matrix))

Alternatively, itertools.chain.from_iterable(matrix) directly accepts the nested list and may be more readable when you already have a list of lists.

Step 5: Flatten Using functools.reduce()

Functional programmers might prefer reduce() with operator.iconcat (or a lambda). This accumulates elements by concatenating lists.

from functools import reduce
import operator
flattened = reduce(operator.iconcat, matrix, [])

Note: iconcat modifies the first argument in place; using [] as the initial value ensures a new list is built.

Step 6: Flatten Arbitrarily Nested Lists with Recursion

When you have lists within lists within lists (more than one level of nesting), the previous methods only flatten one level. For arbitrary depth, write a recursive function.

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

flattened = flatten_deep([1, [2, [3, 4]], 5])  # => [1, 2, 3, 4, 5]

This is a custom solution, but it's clear and handles any depth. You can also implement it iteratively with a stack for very deep lists where recursion might hit recursion limits.

Mastering List Flattening in Python: A Step-by-Step Guide
Source: realpython.com

Step 7: Flatten Using NumPy (for Data Science)

If you're working with numerical arrays, NumPy's .flatten() method is fast and idiomatic.

First, convert the nested list to a NumPy array, then call .flatten():

import numpy as np
array = np.array(matrix)
flattened = array.flatten().tolist()

The result is a one‑dimensional list. If you need a NumPy array instead, omit .tolist().

Tips for Success

Choose the method that best fits your use case and coding style. All produce the same flattened result—pick the one that makes your code most maintainable.

Tags:

Related Articles

Recommended

Discover More

Decoding Word2vec: How a Simple Neural Network Learns Language Structure Through PCAHow Prolly Trees Enable Version Control for DatabasesSilent Sabotage: Newly Revealed Fast16 Malware Targeted Iran with Precision Calculation Tampering Before StuxnetSamsung Joins the Trillion-Dollar Club as Apple Explores Chip Supply Options10 Reasons Why This $444 Off AMD Gaming PC Combo Is an Absolute Steal