Menu Close

How to make a flat list out of a list of lists with Python?

Sometimes, we want to make a flat list out of a list of lists with Python.

In this article, we’ll look at how to make a flat list out of a list of lists with Python.

How to make a flat list out of a list of lists with Python?

To make a flat list out of a list of lists with Python, we can use the sum function.

For instance, we write:

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

We call sum with sublist and an empty array to put all the entries of the nested arrays into the empty array and return it.

Therefore flat_list is [1, 2, 3, 4, 5, 6, 7, 8, 9].

Conclusion

To make a flat list out of a list of lists with Python, we can use the sum function.

Posted in Python, Python Answers