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.
This is just a dummy list to understand the tricks. You may choose a different list as per your scenario.
In this step, we will try to flatten the list. In order to achieve this, we have two methods.
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]
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.
Now let’s see when we use Method 2. Here is the output for that.
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.
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.