Flatten a List of Lists in Python (original) (raw)

Last Updated : 17 Dec, 2024

Flattening a list of lists means turning a nested list structure into a single flat list. This can be useful when we need to process or analyze the data in a simpler format. In this article, we will explore various approaches to **Flatten a list of Lists in Python.

itertools module provides a function called chain which can be used to flatten the list of lists. It is very efficient for large datasets.

Python `

import itertools

Given a list of lists

a = [[1, 2, 3], [4, 5], [6, 7]]

Using itertools.chain to flatten the list

b = list(itertools.chain.from_iterable(a))

print(b)

`

Output

[1, 2, 3, 4, 5, 6, 7]

There are various other ways to Flatten a List of Lists in Python.

Table of Content

Using numpy.concatenate

If we are dealing with numeric data, the numpy library provides a very efficient way to flatten lists using concatenate.

Python `

import numpy as np

Given a list of lists

a = [[1, 2, 3], [4, 5], [6, 7]]

Using numpy.concatenate to flatten the list

b = np.concatenate(a).tolist()

print(b)

`

Output

[1, 2, 3, 4, 5, 6, 7]

reduce() function from the functools module can also be used to flatten a list by applying a function that concatenates lists together.

Python `

from functools import reduce

Given a list of lists

a = [[1, 2, 3], [4, 5], [6, 7]]

Using reduce to flatten the list

b = reduce(lambda x, y: x + y, a)

print(b)

`

Output

[1, 2, 3, 4, 5, 6, 7]

Using List Comprehension

List comprehension is a more way to flatten the list. It condenses the same logic of for loop into a single line.

Python `

Given a list of lists

a = [[1, 2, 3], [4, 5], [6, 7]]

Using list comprehension to flatten the list

b = [item for sublist in a for item in sublist]

print(b)

`

Output

[1, 2, 3, 4, 5, 6, 7]

Using sum() Function

sum() function can be used to flatten a list of lists. It works by starting with an empty list and adding each sublist to it.

Python `

a = [[1, 2, 3], [4, 5], [6, 7]]

Using sum to flatten the list

b = sum(a, [])

print(b)

`

Output

[1, 2, 3, 4, 5, 6, 7]

The most basic way to flatten a list of lists is by using a simple for loop. We loop over each sublist inside the main list and append each item to a new list.

Python `

a = [[1, 2, 3], [4, 5], [6, 7]]

Flattening the list using a for loop

b = [] for sublist in a: for item in sublist: b.append(item)

print(b)

`

Output

[1, 2, 3, 4, 5, 6, 7]

Similar Reads

Python List Access





List Iteration Operations





Python List Search Operations






Python List Remove Operations






Python List Concatenation Operations