Flatten an irregular or arbitrarily nested list of lists in Python
Hello programmers, in this tutorial we will see how to flatten an irregular nested list of lists in Python.
A list enclosing more than one or more lists within itself is called a nested list in Python.
Flattening nested lists helps us get all the elements in a list within the list to a single list which can be used for further manipulations.
There are various different ways to flatten an irregular nested list of lists in Python. We will some of the common ways of achieving the result.
Using a simple ‘for loop’ and the inbuilt method ‘extend()’
The extend() method iterates over the list and adds it at the end of the list. Given below is the solution for using the for loop and the extend() method.
#flatten a nested list def flattenArbList(arbList: list[int]) -> list[int]: res = [] for i in arbList: #for elements in the list if type(i) == list: #if the element is a list res.extend(flattenArbList(i)) #extend and recursively call the function else: res.append(i) #if element, add to the resultant list return res #driver if __name__ == "__main__": exampleList = [1,2,[[3,4],[5]],6,7,[9,10]] print(f"The flattened list of {exampleList} is: {flattenArbList(exampleList)}.")
Output
The flattened list of [1, 2, [[3, 4], [5]], 6, 7, [9, 10]] is: [1, 2, 3, 4, 5, 6, 7, 9, 10].
Explanation
We create a result list in which we append the values of the arbitrary nested list values. If the element is a list, we call the function recursively and add the list elements. If the element is not a list and is directly an element in the main list, we append the element directly to the result list.
Using list comprehension to Flatten an irregular or arbitrarily nested list of lists
List comprehension helps us minimize the code and helps in getting our desired result in fewer lines than usual. Given below is the solution by using list comprehension.
#flatten a nested list def flattenArbList(arbList: list[int]) -> list[int]: return [i for nestList in arbList for i in nestList] #driver if __name__ == "__main__": exampleList = [[1,4,5],[9,10],[2,7],[3,6,8]] print(f"The flattened list of {exampleList} is: {flattenArbList(exampleList)}.")
Output
The flattened list of [[1, 4, 5], [9, 10], [2, 7], [3, 6, 8]] is: [1, 4, 5, 9, 10, 2, 7, 3, 6, 8].
Explanation
We use two loops inside the list comprehension to get the values and print the resultant list.
Using a recursive function to do the same
Given below is the solution using a recursive call of the function.
#flatten a nested list def flattenArbList(arr: list[int]) -> list[int]: if not arr: #if array is empty return [] if isinstance(arr[0], list): #if first element is a list return flattenArbList(arr[0]) + flattenArbList(arr[1:]) #recursively call the function return arr[:1] + flattenArbList(arr[1:]) #recursively call the function #driver if __name__ == "__main__": exampleList = [1, 2, [[3, 4], [5]], 6, 7, [9, 10]] print(f"The flattened list of {exampleList} is: {flattenArbList(exampleList)}.")
Output
The flattened list of [1, 2, [[3, 4], [5]], 6, 7, [9, 10]] is: [1, 2, 3, 4, 5, 6, 7, 9, 10].
Explanation
We return an empty array if there exists no element in the list. If an instance of a list is found inside the main list, the function is called recursively until the elements in the list are flattened.
Using chain from Itertools module to flatten an irregular nested list of lists
The ‘chain’ method from the Itertools module in Python groups all the iterators and return a single iterable. Given below is the solution by using the chain function from the itertools module.
#Import libraries import itertools #flatten a nested list def flattenArbList(arr: list[int]) -> list[int]: return list(itertools.chain.from_iterable(arr)) #driver if __name__ == "__main__": exampleList = [[1, 4, 5], [9, 10], [2, 7], [3, 6, 8]] print(f"The flattened list of {exampleList} is: {flattenArbList(exampleList)}.")
Output
The flattened list of [[1, 4, 5], [9, 10], [2, 7], [3, 6, 8]] is: [1, 4, 5, 9, 10, 2, 7, 3, 6, 8].
Explanation
We return a list of the single iterable returned from the ‘chain’ function of the input array.
Leave a Reply