Trusted answers to developer questions

How to flatten a list of lists in Python

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

Converting a list of lists (2D), into a list (1D) is called flattening. There are several approaches to this problem. We will look at a few important ones.

svg viewer

Approaches to flattening lists


Nested loops

This is perhaps the most intuitive approach to flattening​. We pick every element from the list of lists and put it into our flat list.

List_2D = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattened
List_flat = []
for i in range(len(List_2D)): #Traversing through the main list
for j in range (len(List_2D[i])): #Traversing through each sublist
List_flat.append(List_2D[i][j]) #Appending elements into our flat_list
print("Original List:",List_2D)
print("Flattened List:",List_flat)

Functools (reduce-iconcat)

Perhaps the fastest execution can be achieved through this approach. However, it isn’t very intuitive and requires importing a few libraries.

import functools
import operator
List_2D = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattened
List_flat = functools.reduce(operator.iconcat, List_2D, [])
print("Original List:",List_2D)
print("Flattened List:",List_flat)

Itertools(chain)

This is another notable approach. Although not as fast as the previous one, it’s still faster than using Nested-loops.

import itertools
List_2D = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattened
List_flat = list(itertools.chain(*List_2D))
print("Original List:",List_2D)
print("Flattened List:",List_flat)

Other approaches

The approaches we discussed so far are a few of the fastest known ones. However, there are other approaches to the problem, ​including:

  • Functools - reduce
  • NumPy - concatenate
  • NumPy - flat
  • Summing inner lists

RELATED TAGS

python
lists
list of lists
flatten
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?