How to Make a Flat List out of a List of Lists in Python?

Spread the love

Problem –

You want to create a flat list out of list of lists in python.

In [1]: list_of_lists = [[1, 2, 3], [4, 5, 6], [7], [8,9]]

Solution –

To flatten the list of lists we can use a list comprehension.

In [2]: flat_list = [item for list in list_of_lists for item in list]

In [3]: flat_list
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

This is equivalent to

In [4]: flat_list = []

In [5]: for list in list_of_lists:
   ...:     for item in list:
   ...:         flat_list.append(item)
   ...:         

In [6]: flat_list
Out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Rating: 1 out of 5.

Leave a Reply