As a programmer, you may encounter situations where you need to convert a list of lists into a single, flat list.
This can be a simple task in Python, and it can be achieved using several methods.
In this tutorial, we will explore how to create a flat list from a list of lists in Python using both traditional and modern methods.
Method 1: Using a For Loop
One of the simplest methods to create a flat list from a list of lists is by using a for loop.
In this method, you iterate through each list and add its elements to the final list.
Here’s an example:
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat_list = [] for sublist in list_of_lists: for item in sublist: flat_list.append(item) print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 2: Using List Comprehension
Another popular method to create a flat list from a list of lists is by using list comprehension.
List comprehension is a concise and efficient way of performing operations on lists.
Here’s an example:
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]
Method 3: Using the itertools Module
The itertools module in Python provides a chain function, which can be used to create a flat list from a list of lists.
Here’s an example:
import itertools list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat_list = list(itertools.chain(*list_of_lists)) print(flat_list)
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Conclusion
In this article, we explored three methods to create a flat list from a list of lists in Python.