How to flatten a list of lists in Python?

Apr 13, 2022 10:29 · 185 words · 1 minute read Python

There is an obvious solution to the problem of flatten the nested lists, which is

new_list = [item for sublist in t for item in sublist]

However, there are other more effective solutions out there.

Pure Python

the_list = [[1, 2, 3], [1, 2], [8, 9]]
new_list = [i for sublist in the_list for i in sublist]

# Output: [1, 2, 3, 1, 2, 8, 9]

Itertools package

import itertools

the_list = [[1, 2, 3], [1, 2], [8, 9]]

new_list = list(itertools.chain.from_iterable(the_list))

# Output: [1, 2, 3, 1, 2, 8, 9]

Functools package (Reduce)

from functools import reduce
import operator

the_list = [[1, 2, 3], [1, 2], [8, 9]]
new_list = reduce(operator.concat, the_list)

# Output: [1, 2, 3, 1, 2, 8, 9]

Numpy solution

import numpy

the_list = [[1, 2, 3], [1, 2], [8, 9]]

new_list = numpy.concatenate(the_list)

# Output: [1, 2, 3, 1, 2, 8, 9]

Python recursive solution

def flatten(itr):
    for x in itr:
        try:
            yield from flatten(x)
        except TypeError:
            yield x

the_list = [[1, [2], 3], [[1], 2], [8, 9]]

new_list = flatten(the_list)

# Output: [1, 2, 3, 1, 2, 8, 9]

We will notify you about new posts every few weeks