How to Flatten a List of Lists in Python
If you have a list of lists in Python and you want to flatten it (i.e., convert it into a single flat list), there are several approaches you can take. In this article, we will explore different methods to solve this problem.
Method 1: Using Nested Loops
One way to flatten a list of lists is by using nested loops. You can iterate through each sublist and append its elements to a new flat list.
def flatten_list(lst):
flat_list = []
for sublist in lst:
for element in sublist:
flat_list.append(element)
return flat_list
# Example usage:
my_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
result = flatten_list(my_list)
print(result)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
This method works by iterating through each sublist in the input list and then iterating through each element in the sublist. It appends each element to a new flat list, which is then returned as the result.
Method 2: Using List Comprehension and the extend() Method
Another approach is to use list comprehension and the extend() method. List comprehension allows you to create a new list by iterating over each sublist and its elements. The extend() method is used to add the elements of each sublist to the new list.
def flatten_list(lst):
flat_list = []
[flat_list.extend(sublist) for sublist in lst]
return flat_list
# Example usage:
my_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
result = flatten_list(my_list)
print(result)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this method, list comprehension is used to iterate over each sublist in the input list. The extend() method is called to add the elements of each sublist to the new flat list. The new list is then returned as the result.
Method 3: Using itertools.chain() and the * Operator
The itertools module in Python provides a chain() function that can be used to concatenate multiple iterables. By using the * operator with the input list, we can pass each sublist as a separate argument to the chain() function and flatten the list.
import itertools
def flatten_list(lst):
return list(itertools.chain(*lst))
# Example usage:
my_list = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
result = flatten_list(my_list)
print(result)
# Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this method, we import the itertools module and use the chain() function to concatenate the sublists. The * operator is used to unpack the elements in the input list and pass them as separate arguments to the chain() function. The resulting chained object is then converted to a list using the list() function and returned as the result.
Conclusion
Flattening a list of lists in Python can be achieved using a variety of methods. Whether you prefer nested loops, list comprehension, or itertools, there are multiple ways to solve this problem. By choosing the method that best fits your needs and requirements, you can easily flatten any nested lists in your Python programs.