![]() |
VOOZH | about |
In this article, we will cover how to Flatten a List of Lists in python. To convert a nested list into a flat list we are going to see some examples.
Example:
Input : l = [1, 2, [3, 4, [5, 6] ], 7, 8, [9, [10] ] ] Output : l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Input : l = [[['item1', 'item2']], [['item3', 'item4']]] Output : l = ['item1', 'item2', 'itm3, 'item4'']
A list within a list (or a list within another nested list). The task is to convert a nested list into a single list in python i.e no matter how many levels of nesting is there in the python list, all the nested have to be removed in order to convert it to a single containing all the values of all the lists inside the outermost brackets but without any brackets inside.
In this article, we will cover 5 different approaches to flat a list of lists.
In this example, we will see that we are Iterating the outer list first and then if there is a sub-list then we are iterating the sub-list using for loop. After that, we are appending the element in our new list "flatList" which gives us a flat list of 1 dimensional.
Output:
List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]] Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
Time Complexity: O(n)
Auxiliary Space: O(n)
In this example, we will use list comprehension to Iterate the list first, and then we are iterating the sub-list using for loop. After that, we are appending the element in our new list "flatList" using a List Comprehension which gives us a flat list of 1 dimensional.
Output:
List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]] Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
In this example, We are using the recursion method to flat a nested list with multiple levels of nesting.
The original list: [1, 2, [3, 4, [5, 6]], 7, 8, [9, [10]]] The list after removing nesting: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
In this example, we are using a pandas module, pandas have a method called np.concatenate which helps us to flat a nested list.
Output:
[11, 33, 22, 55, 11, 77, 88]
In this example, we are using a python In-build sum() method which will give us a flat list.
Output:
New list [11, 22, 33, 44, 55, 66, 77, 88, 99]
The functools module offers ways to use and extend other functions and callable objects without having to totally rewrite them.
Output:
List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]] Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
Python’s Itertool is a module that provides various functions that work on iterators to produce complex iterators.
Output:
List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]] Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]
List [[11, 22, 33, 44], [55, 66, 77], [88, 99, 100]] Flat List [11, 22, 33, 44, 55, 66, 77, 88, 99, 100]