+ 1
Why I am getting empty list with this code. Can anyone explain?
This is a code from list comprehension in python car = ["Maruti","Swift","Ford","Bugati"] newlist = [x for x in car if x != "Maruti" in x ] print(newlist) # this is the simple code please explain
7 Respuestas
+ 2
Aman Kumar the list comprehension is just equivalent to :
newlist=[ ]
for x in car:
if x!="Maruti":
newlist.append(x)
Hope you got it .
+ 4
Calvin Thomas is correct. You essentially have a chained 'and' logical statement. If you remove the 'in x' from the end of the list comprehension, you will result in a list with all the elements minus "Maruti". The reason it is otherwise empty is because the only condition in which "Maruti" in x is True is the first where x is "Maruti", and for that element x != "Maruti" is False so for every evaluation of the conditional, the result is likewise, False.
+ 3
In my opinion, the logic simplifies to 'x != "Maruti" and "Maruti" in x', which is False considering the data here. I guess that this needs some clarification, though.
+ 2
In order to get desired results the list comprehension should be :
newlist=[x for x in car if x!="Maruti" ]
Remember we can find x in car only then it'll be true and if you wanna find x in x then it'll return false .
+ 2
As a beginner i am still confused🤔🤔🤔🤔🤔🤔🤔🤔
+ 2
Aman Kumar
it's simply finding all the values from the list car whose value not equal to "Maruti" and making an another list named newlist of all those values .
That is
print (newlist) would give
["Swift","Ford","Bugati"]
Hope you understand
0
Can anyone explain
I got confused in lists comprehension.