How to flatten a nested list in Python

In Python, we usually encounter nested lists which need to be flattened. There are multiple methods to flatten a nested list using loops. However, an efficient way to do it is using comprehensions.

Description

Comprehensions are used to generate an iterable object in Python with minimum and concise code.

Code

In the code below, nested_list is flattened using both a comprehension and a loop to see if both the methods produce the same results. It also helps us understand how comprehension works.

The x in a comprehension is the element of each sublist sub of the nested_list. The comprehension extracts each element of each list of the nested_list and appends it to the final flat list.

With the help of comprehension` the code looks cleaner and is more concise, as compared to the loop.

nested_list = [[1,2,3,4],[5,6,7],[8,9,10],[0.1,0]]
flat = [x for sub in nested_list for x in sub]
print ("Flat list using comprehension", flat)
flat = []
for sub in nested_list:
for x in sub:
flat.append(x)
print ("Flat list using loop", flat)

Free Resources