To flatten a list of lists in Python, the easiest way is to use list comprehension.
list_of_lists = [[1], [2, 3], [4, 5, 6]]
flattened_list = [value for sub_list in list_of_lists for value in sub_list]
print(flattened_list)
#Output:
[1, 2, 3, 4, 5, 6]
If you have a list of lists which also contain lists of lists, you can use a recursive function to flatten all levels of the list of lists.
list_of_lists = ["a", ["b", "c"], [1, [2, 3]], [4, 5], 6]
def flatten_list(lst):
flat_list = []
for item in lst:
if type(item) == list:
flat_list = flat_list + flatten_list(item)
else:
flat_list.append(item)
return flat_list
print(flatten_list(list_of_lists))
#Output:
['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
When working with collections of data, the ability to easily be able to manipulate them and change the structure is valuable.
One such case is if you have an array of arrays and want to flatten them into one array.
Arrays in Python are called lists, and we can easily flatten a list in Python.
To flatten a list of lists in Python, the easiest way is to use list comprehension. This method works if you have a list of lists and each of those sub-lists do not contain lists.
The idea here is that for each list, we want to get all of the values and then store them in a new list.
Below shows you how to use list comprehension to flatten a list of lists in Python.
list_of_lists = [[1], [2, 3], [4, 5, 6]]
flattened_list = [value for sub_list in list_of_lists for value in sub_list]
print(flattened_list)
#Output:
[1, 2, 3, 4, 5, 6]
Using Recursion to Flatten List of Multi-dimensional Lists in Python
If you have a list of objects where some are not lists and others are lists or lists of lists, we need to do some more work to flatten a list like this.
You can use recursion to flatten a list of multi-dimensional lists in Python.
The idea here is that you have to loop over each item of the list and then if that item is of type list, we need to get the values of that list as well.
Then, you can use the concatenation operator + to add the list items together.
Below is a function which will flatten a list of lists with multiple dimensions in Python.
list_of_lists = ["a", ["b", "c"], [1, [2, 3]], [4, 5], 6]
def flatten_list(lst):
flat_list = []
for item in lst:
if type(item) == list:
flat_list = flat_list + flatten_list(item)
else:
flat_list.append(item)
return flat_list
print(flatten_list(list_of_lists))
#Output:
['a', 'b', 'c', 1, 2, 3, 4, 5, 6]
Hopefully this article has been useful for you to learn how to flatten lists in Python.