A flat list out of a list of lists
How to make a flat list out of a list of lists? – Part 2.
In the previous article, we have discussed a few methods of flattening lists. So, before we move forward to learn more about these approaches, please refer to Part 1 of this article.
The approaches we’ll discuss in this article are mostly using libraries and inbuilt functions
Using functools (reduce() and iconcat())
Using itertools (chain())
Using numpy (concatenate() and flat())
Like in the previous article, we used the same list List as an example which is a list of lists with the following elements and have an empty list named flat_list where we store the final flattened list.
Using functools (reduce() and iconcat()):
We import the libraries, functools and operator for implementing this approach. The basic syntax is:
functools.reduce(operator.iconcat, Original_List, [ ])
The iconcat() function performs concatenation. This gets applied cumulatively to the inner lists of the list List starting from left to right, which finally reduces to a single list.
Using itertools (chain()):
This is one of the most ideal ways for this process of flattening. We import the itertools library to implement this approach. This library has various functions. These functions can be used to manage iterators which iterate through the iterables like lists and strings easily. These Itertools don’t work as fast as the functools, but work much better than a nested-loop. These itertools treat consecutive sequences as a single sequence by iterating through the iterable which is passed as an argument in a sequential manner. The general syntax is:
list( itertools.chain (*iterable))
Using numpy (concatenate() and flat()):
We import the numpy package to implement this approach. It offers common operations like row-wise and column-wise operations on 2D arrays such as concatenating. The basic syntax is:
list( numpy.concatenate(List).flat )
The flat attribute here is used to get a 1D iterator over the array. But this approach is relatively slow.
In this approach, we sum up the inner lists. This sum() function takes in two parameters: iterable and start. The iterable is a list of lists and start is an empty list in which we will add the sublist.
sum( List, [ ])
We don’t necessarily import any library here, but this approach is slower than itertools() and the chain() functions especially when the number of sublists is large.