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]