a shot of dev knowledge

RELATED TAGS

# How to flatten a list of lists in Python

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.

## 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

RELATED COURSES
View all Courses
Related Courses
RELATED COURSES
View all Courses
Keep Exploring

Learn in-demand tech skills in half the time