How do I make a flat list out of a list of lists?
To create a flat list out of a list of lists, you can use the itertools.chain
function from the itertools
module in the Python standard library. This function takes a list of lists as input and returns a new iterator that sequentially yields the elements of each list.
Here's an example of how you can use itertools.chain
to create a flat list:
import itertools
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = list(itertools.chain.from_iterable(list_of_lists))
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Watch a video course
Python - The Practical Guide
You can also use a list comprehension to create a flat list.
Here's an example of how you can do this:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat_list = [item for sublist in list_of_lists for item in sublist]
print(flat_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Both of these approaches will create a new list that contains all of the elements from the input list of lists, in the order that they appear.