How to flatten a list in Python?

Better Stack Team
Updated on January 24, 2023

You can flatten a list in python using the following one-liner:

 
flat_list = [item for sublist in l for item in sublist]

In the example above, l is the list of lists that is to be flattened.

The previous example can be rewritten to be more readable and will look like this:

 
flat_list = []
for sublist in l:
    for item in sublist:
        flat_list.append(item)

You can wrap this functionality into a function if you prefer:

 
def flatten(l):
    return [item for sublist in l for item in sublist]
Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →

Reliability is the
ultimate feature

Delightful observability tools that turn your logs & monitoring into a secret weapon for shipping better software faster.

Explore Better Stack