Menu

How to Flatten a List of Lists in Python
📰

How to Flatten a List of Lists in Python

DEV Community: tutorial·Peakblick·15 days ago
#93qWhiao
#devtotutorial#devto#dev#nested#list
Reading 0:00
15s threshold

You have a list of lists — [[1, 2], [3, 4], [5, 6]] — and you want one flat list: [1, 2, 3, 4, 5, 6] . There are three good ways to do it and one popular way that quietly gets slow. Here's each, when to use it, and the one mistake everyone makes.

The quick answer

The most Pythonic one-liner is a nested list comprehension :

nested = [[ 1 , 2 ], [ 3 , 4 ], [ 5 , 6 ]] flat = [ x for row in nested for x in row ] # [1, 2, 3, 4, 5, 6]

Enter fullscreen mode

Exit fullscreen mode

If you don't need a list specifically — just to iterate — itertools.chain.from_iterable is the cleanest and fastest. Both are below.

1. Nested list comprehension

Read the two for clauses left to right, exactly in the order you'd write nested loops:

flat = [ x for row in nested for x in row ]

# the same thing as an explicit loop: flat = [] for row in nested : # outer first for x in row : # inner second flat .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.