As you know list is a data structure that stores multiple objects or variables in a single variable. You can easily manipulate a list using various built-in functions. In this post, you will learn the different methods to flatten a List of Lists in Python
What is Flattening of List?
Flattening a list is a process where you convert a nested list that is a list of lists to a single single-dimensional list. Thus it preserves the order of all the elements of the list.
Methods on How to Flatten a List of Lists in Python
Let’s know all the methods to flatten a list of lists in Python.
Method 1: Using List Comprehension
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [element for sublist in nested_list for element in sublist]
print(flattened_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 2: Using Nested Loops
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = []
for sublist in nested_list:
for element in sublist:
flattened_list.append(element)
print(flattened_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 3: Using the itertools module
The itertools module in Python provides a function called chain.from_iterable()
that can be used to flatten a list of lists.
from itertools import chain
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = list(chain.from_iterable(nested_list))
print(flattened_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 4: Using the sum() Function
You can use the sum()
function to concatenate the nested lists and create a flattened list.
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = sum(nested_list, [])
print(flattened_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 5: Using Recursion
Recursion can be used to handle nested lists of any depth and flatten them.
def flatten_list(nested_list):
flattened_list = []
for element in nested_list:
if isinstance(element, list):
flattened_list.extend(flatten_list(element))
else:
flattened_list.append(element)
return flattened_list
nested_list = [[1, 2, [3]], [4, [5, 6]], [7, 8, 9]]
flattened_list = flatten_list(nested_list)
print(flattened_list)
Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Conclusion
In order to preserve the order of the elements of the list you have to flatten the list of lists. The above methods allow you to convert the nested list to a single-dimensional list. You can use any methods defined here as per convenience.
Leave a Reply