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.
x = ["Mohan", "Kriti", "Salim"] y = [i for i in x] print("The new List is ",y)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Then we have used List Comprehension,
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'.
And we get the below output.
Let us see another example, where you need to create a new List which would only contain the value 'Kriti' from the previous List.
x = ["Mohan", "Kriti", "Salim"] y = [i for i in x if 'Kriti' == i] print("The new List is ",y)
So, in the above code we have created a 'List' and initialised to the variable 'x'.
Below is how the values are positioned in the List,
Then we have used List Comprehension,
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').
And we get the below output.