How can I flatten a list of lists in Python?

Discussion RoomCategory: CodingHow can I flatten a list of lists in Python?
Admin Staff asked 1 month ago

To flatten a list of lists in Python, you can use list comprehension or the itertools.chain function. Here’s how you can do it using list comprehension:

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = [item for sublist in nested_list for item in sublist]
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Alternatively, you can use itertools.chain:

from itertools import chain

nested_list = [[1, 2, 3], [4, 5], [6, 7, 8]]
flat_list = list(chain.from_iterable(nested_list))
print(flat_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

Both approaches will give you a flat list containing all the elements from the nested lists.

Scroll to Top