list
python

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

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Python, you can flatten a list of lists into a single flat list using various methods. Here are some of the most common approaches:

1. Using a List Comprehension

List comprehensions provide a concise way to flatten a list of lists:

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

Output:

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

2. Using itertools.chain

The itertools.chain function is another efficient way to flatten a list of lists:

python
1import itertools
2
3list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
4flat_list = list(itertools.chain(*list_of_lists))
5
6print(flat_list)

Output:

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

Alternatively, you can also use itertools.chain.from_iterable which avoids the unpacking of the list:

python
flat_list = list(itertools.chain.from_iterable(list_of_lists))

3. Using sum()

Although less common, you can use sum() with an empty list as the start value:

python
1list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
2flat_list = sum(list_of_lists, [])
3
4print(flat_list)

Output:

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

4. Using functools.reduce

You can also use functools.reduce to flatten a list of lists:

python
1from functools import reduce
2
3list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
4flat_list = reduce(lambda x, y: x + y, list_of_lists)
5
6print(flat_list)

Output:

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

5. Using numpy (if your lists are numerical and you have NumPy installed)

If you're dealing with numerical data, you can use numpy's flatten method:

python
1import numpy as np
2
3list_of_lists = [[1, 2, 3], [4, 5], [6, 7, 8]]
4flat_list = np.array(list_of_lists).flatten().tolist()
5
6print(flat_list)

Output:

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

Summary

  • List Comprehension: Simple and Pythonic.
  • itertools.chain: Efficient for large lists.
  • sum(): Simple but less efficient for large lists.
  • functools.reduce: Less common, but a functional approach.
  • numpy.flatten: Great for numerical data, but requires NumPy.

The best method depends on your specific use case, but list comprehension and itertools.chain are generally the most common and efficient ways to flatten a list of lists in Python.


Course illustration
Course illustration

All Rights Reserved.