Nested list comprehension python : Easy Tricks for you

Nested list comprehension python

Nested list comprehension python is creating a new list from the nested list. In this article, we will see how to achieve Nested list comprehension python step by step.

 

Nested list comprehension python (Step By Step)-

Well, Nested list comprehension looks tricky in beginning. But If we do it step by step, this comprehension becomes so easy.

Step 1 :

This is a prerequisite step where we will create a nested list.

var_list=[[1,2,4],[3,6],[8],[2,5,6,6,3]]

This is just a dummy list to understand the tricks. You may choose a different list as per your scenario.

Step 2:

In this step, we will try to flatten the list. In order to achieve this, we have two methods.

Method 1:

This is an inline method for Nested list comprehension. All you need to use the below line to flatten the complete list.

flattened_list = [ ele for inner_list in var_list for ele in inner_list]

Method 2:

Unlike, Above we have scattered the looping in multiline code. This makes code more readable because of its logical reflection. Here is the code sample for this.

flattened_list = [] 
for inner_list in var_list: 
    for ele in inner_list: 
        flattened_list.append(ele) 

See, Here we have used two-level nesting. But if you have more complex or nested list. You need to adjust the looping accordingly.

Complete Code at a place –

When we integrate step 1 and step 2 together. We get the following output.

"<yoastmark

Now let’s see when we use Method 2. Here is the output for that.

"<yoastmark

Conclusion –

Well, Nested List comprehension is really easy when we do it in steps. In the First step, we have initiated a python list with some dummy data. In the second step, we have flattened it and created a new list. These two-steps together become python Nested list comprehension.

I hope you must have found this article useful. But It will be great when you write back to us. You may comment on us in the below comment box.

Thanks 

Data Science Learner Team

Join our list

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.

Thank you for signup. A Confirmation Email has been sent to your Email Address.

Something went wrong.

Meet Abhishek ( Chief Editor) , a data scientist with major expertise in NLP and Text Analytics. He has worked on various projects involving text data and have been able to achieve great results. He is currently manages Datasciencelearner.com, where he and his team share knowledge and help others learn more about data science.
 
Thank you For sharing.We appreciate your support. Don't Forget to LIKE and FOLLOW our SITE to keep UPDATED with Data Science Learner