Q&A

Questions &
Answers with MarsDevs

HTML & CSS
JavaScript

How do I make a flat list out of a list of lists?

Solution:

There are many ways in Python to flatten a list of lists.

First, you can use list comprehension.


nested_list = [[1,2,3], [4,5,6],[7,8,9]]

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

print(flat_list)

Next, you can use itertools.chain. Here’s an example.


from itertools import chain

nested_list = [[1,2,3], [4,5,6],[7,8,9]]

flat_list = list(chain(*nested_list))

print(flat_list)

The itertools.chain function concatenates the sublists into a single iterable and then converts them to a list. Lastly, you can also use itertools.chain.from_iterable.


from itertools import chain

nested_list = [[1,2,3], [4,5,6],[7,8,9]]

flat_list = list(chain.from_iterable(nested_list))

print(flat_list)

Here, itertools.chain.from_iterable achieves the same result as chain(*nested_list).

Ultimately, all methods will have a flattened list [1, 2, 3, 4, 5, 6, 7, 8, 9].

Want to know more about Python? Check out our blogs!