Why and/or operations in python statement are behaving unexpectedly?

  • A+

I have a conceptual doubt in Python. This is the code

list1=['assistant manager', 'salesperson', 'doctor', 'production manager', 'sales manager', 'schoolteacher', 'mathematics teacher'] sub1 = "teacher" sub2 = "sales" ans=[]  for item in list1:     if (sub1 and sub2) in item:         ans.append(item) 

Here, I expect the list to be empty as none of the items satisfy the condition if sub1 and sub2 in item: But when I print the list I get the output#1 as this

>>> ans ['salesperson', 'sales manager'] # I expected an empty list here 

Also, when I use or instead of and as given below

for item in list1:     if (sub1 or sub2) in item:         ans.append(item) 

the output#2 I get is

>>> ans ['schoolteacher', 'mathematics teacher'] # I expected a list of words containing sub1 or sub2 as their substrings 

I saw a similar looking solution here, but it does not exactly solve my problem. Both the times I get a result which I do not expect while using and and or. Can someone please explain why is this happening during both these operations?


("teacher" and "sales") in "salesmanager" do not mean the same in Python and in English.

In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager") (which Python would understand as you thought it should, and evaluate to False).

Python on the other hand will first evaluate "teacher" and "sales", because it is in parentheses, and thus has higher priority. and will return the first argument if falsy, otherwise the second argument. "teacher" is not falsy, so "teacher" and "sales" evaluates as "sales". Then, Python continues to evaluate "sales" in "salesmanager", and returns True.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: