Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




PYTHON - LIST COMPREHENSION


What is List Comprehension ?


List Comprehension is used, when you are trying to create a new List based on the values of the existing List.


Let us understand with the below example.


Example :


x = ["Mohan", "Kriti", "Salim"] 
y = [i for i in x]
print("The new List is ",y) 


Output :



  The new List is ['Mohan', 'Kriti', 'Salim']

So, in the above code we have created a 'List' and initialised to the variable 'x'.


x = ["Mohan", "Kriti", "Salim"]

Below is how the values are positioned in the List,


java_Collections

Then we have used List Comprehension,


y = [i for i in x]

Where '[i for i in x]' is a code written in shorter way and it means,


y = []
for i in x:
    y.append(i)

And the new List 'y' is an exact copy of 'x'.


java_Collections

And we get the below output.


The new List is ['Mohan', 'Kriti', 'Salim']

Let us see another example, where you need to create a new List which would only contain the value 'Kriti' from the previous List.


Example :


x = ["Mohan", "Kriti", "Salim"] 
y = [i for i in x if 'Kriti' == i]
print("The new List is ",y)  


Output :



  The new List is ['Kriti']

So, in the above code we have created a 'List' and initialised to the variable 'x'.


x = ["Mohan", "Kriti", "Salim"]

Below is how the values are positioned in the List,


java_Collections

Then we have used List Comprehension,


y = [i for i in x if 'Kriti' == i]

Where '[i for i in x if 'Kriti' == i]' is a code written in shorter way and it means,


y = []
for i in x:
    if i == 'Kriti':
        y.append(i)

And the new List 'y' is created with only one value of 'x' (i.e. 'Kriti').


java_Collections

And we get the below output.


The new List is ['Mohan', 'Kriti', 'Salim']