+ 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

19th Apr 2021, 1:28 AM
Aman Kumar
Aman Kumar - avatar
7 Antworten
+ 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 .
19th Apr 2021, 4:56 AM
Akshay Panwar
Akshay Panwar - avatar
+ 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.
19th Apr 2021, 2:17 AM
ChaoticDawg
ChaoticDawg - avatar
+ 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.
19th Apr 2021, 1:51 AM
Calvin Thomas
Calvin Thomas - avatar
+ 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 .
19th Apr 2021, 4:53 AM
Akshay Panwar
Akshay Panwar - avatar
+ 2
As a beginner i am still confused🤔🤔🤔🤔🤔🤔🤔🤔
19th Apr 2021, 4:59 AM
Aman Kumar
Aman Kumar - avatar
+ 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
19th Apr 2021, 5:04 AM
Akshay Panwar
Akshay Panwar - avatar
0
Can anyone explain I got confused in lists comprehension.
19th Apr 2021, 1:29 AM
Aman Kumar
Aman Kumar - avatar