How to flatten a list of lists in Python

Jul 02, 2024#python

A list of lists in Python is a list where each element is itself a list. This can be useful for representing data in a tabular form, like a matrix or a 2D array.

# Creating a list of lists
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Accessing elements
print(matrix[0])     # Output: [1, 2, 3]
print(matrix[0][1])  # Output: 2

# Iterating through a list of lists
for row in matrix:
    for element in row:
        print(element, end=' ')
    print()

Flattening a list of lists means converting a list that contains sublists into a single list containing all the elements of the sublists. Here are some common methods:

  1. Using nested loops. This is a basic approach where you iterate through the outer list and then iterate through each sublist, appending elements to a new empty list. It’s easy to understand but can be less efficient for larger lists.
def flatten_list(nested_list):
    flat_list = []
    for sublist in nested_list:
        for element in sublist:
            flat_list.append(element)
    return flat_list

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

print(flatten_list(matrix))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
  1. Using list comprehension. This method offers a concise and often faster alternative to nested loops. It iterates through the nested structure in a single line using nested comprehensions.
def flatten_list(nested_list):
    return [element for sublist in nested_list for element in sublist]
  1. Using itertools module, which is part of Python’s standard library. It provides the chain.from_iterable() function which efficiently flattens iterables. It takes an iterable of iterables (like your nested list) and returns a single iterator containing all elements. You can convert this to a list using list().
from itertools import chain

def flatten_list(nested_list):
    return list(chain.from_iterable(nested_list))
  1. Using functools.reduce() function from functools along with the operator.concat function to achieve flattening. It applies concat successively to elements in the list, flattening the structure.
from functools import reduce
from operator import concat

def flatten_list(nested_list):
    return reduce(concat, nested_list)