Converting a list of lists (2D), into a list (1D) is called flattening. There are several approaches to this problem. We will look at a few important ones.
This is perhaps the most intuitive approach to flattening. We pick every element from the list of lists and put it into our flat list.
List_2D = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattenedList_flat = []for i in range(len(List_2D)): #Traversing through the main listfor j in range (len(List_2D[i])): #Traversing through each sublistList_flat.append(List_2D[i][j]) #Appending elements into our flat_listprint("Original List:",List_2D)print("Flattened List:",List_flat)
Perhaps the fastest execution can be achieved through this approach. However, it isn’t very intuitive and requires importing a few libraries.
import functoolsimport operatorList_2D = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattenedList_flat = functools.reduce(operator.iconcat, List_2D, [])print("Original List:",List_2D)print("Flattened List:",List_flat)
This is another notable approach. Although not as fast as the previous one, it’s still faster than using Nested-loops.
import itertoolsList_2D = [[1,2,3],[4,5,6],[7,8,9]] #List to be flattenedList_flat = list(itertools.chain(*List_2D))print("Original List:",List_2D)print("Flattened List:",List_flat)
The approaches we discussed so far are a few of the fastest known ones. However, there are other approaches to the problem, including:
Free Resources