Last time , I talked about python’s boolean operators and and or and what can be confusing about them when “truthy” objects get into the mix. If you haven’t already read it, I would highly recommend it. This article is similar, but looks into something just a little different: the ability to string comparison operators.

The Confusing Code
Just like last time, we’ll start off looking at some code that confused someone enough to ask the community about it:
'a' in 'abc' # True True == True # True 'a' in 'abc' == True # FalseAt a cursory glance, there seems to be something wrong with that it would come up with such a result.But this is caused by a feature of Python that is actually really awesome: the ability to string comparison operators.
Less Confusing CodeThis awesome feature of Python that helps us keeps our code more concise allows us to turn this code:
0 < x and x < 100Into this much more readable code:
0 < x < 100Python actually allows you to do this type of thing indefinitely:
0 < x < 100 < y < zWhich gets expanded to:
0 < x and x < 100 and 100 < y and y < zExcept that it’s optimized so that each variable only needs to be looked up once.
The Confusing PartBut it doesn’t just work with the < , <= , > , and >= operators. It also includes == , != , is , is not , and in . It’s incredibly useful to include the other operators, but they’re not generally expected to be included (especially not in ).
So, let’s go back to the code example:
'a' in 'abc' == TrueGets effectively expanded to:
'a' in 'abc' and 'abc' == TrueTo get the effect that we actually were expecting, we need only to wrap the first part in parenthesis:
('a' in 'abc') == True OutroSome of you may have learned about this cool feature in Python just now, or you may be like me and forgot about it until this brought it up. You may also have already known about it, but I doubt that you were able to figure out the starting code example right away. The feature is great, and can help us express conditions in a clean way that we learned back in elementary or middle school, but you’ve also seen that it can be confusing.
Just keep this feature in the back of your mind when writing conditionals and make sure you keep it doing what you want it to do. When in doubt, paren’ it out!