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.
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:
Create a flat list out of a list of lists, using itertools.chain method
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]
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Python - The Practical Guide</div>
You can also use a list comprehension to create a flat list.
Here's an example of how you can do this:
Create a flat list out of a list of lists, using list comprehension
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.