Python

Flatten List of Lists Python Easily with 4 different ways

Flatten list of lists  python is converging all sub list at the same level (root). There are many tricks in python to flatten list of lists. In this article, We will explore them one by one.

Flatten list of lists python : Various Methods-

 

In this section, We will discuss various ways but before that, we have prerequisites. We need to create a list of lists which we will use throughout the methods.

sample_list = [[11, 42, 31], [8, 45], [8,111,46], [76]]

Method 1: Using itertools-

 

Firstly We will see the implementation. Then we will see the logic part.

import itertools
flat_list = list(itertools.chain(*sample_list))
print(flat_list)

We have used pointer reference in chain function. Then we simply typecast them into the list. Let’s run the code and check out the output.

Method 2: Iterating the sublists-

 

Well, this is one of the most popular ways of flattening. Here we will iterate the sublist and append the element in the final list.

flatten_list = []
for inner_list in sample_list:
    for ele in inner_list:
        flatten_list.append(ele)

Finally when we run this code. We have this output.

flatten list of lists iteration sub list

See, The above code snippet works if list is nested at one inner list only. Let me clearify it, Suppose we have a list in which we have multiple list. But these sub lists do not contain the list as element them.

 

Method 3 : Iterator inline –

 

It is the same way like we have done in section 2 ( Method 2). The only difference is we are doing it in one line (inline).

flatten_list = [ele for inner_list in sample_list for ele in inner_list]
flatten list of lists iteration inline

Method 4 : Using functools module-

 

This is also very simple way to flatten a python list. Here we will import reduce module from functools. In order to make the process inline,

We will use python lambda function. Lets see the implementation with output here.

from functools import reduce 
reduce(lambda l,m: l+m,sample_list)
flatten list using functools reduce method

I think this article has covered most of the way to flatten a python list. Please comment if you now some other and better tricks for this.

Thanks 

Data Science Learner Team