6

Sorry, I couldn't think of a more descriptive title. This isn't super important, but rather a weird quirk in python 3.8 (at least) that I found, and I figured I can't be the only one who's noticed this, and there's probably a reasonable explanation:

>>> 'foo' in 'foobar' == True
False

It works the other way too:

>>> True == 'foo' in 'foobar'
False

However, logically I would think this should be True, as

>>> 'foo' in 'foobar'
True
>>> True == True
True

I'm assuming it's some kind of order of operations error, but when I try to group it I get

>>> ('foo' in 'foobar') == True
True
>>> 'foo' in ('foobar' == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

I'm mostly just really curious at this point, if someone could explain this that'd be great!

1 Answers1

6

Because of operator chaining the expression is equivalent to:

('foo' in 'foobar') and ('foobar' == True)

Since 'foobar' == True is False, the whole expression is False.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Looks exactly right. You can also try evaluating `'foo' in 'foobar' in 'foobarbaz'` (`True`), while adding parentheses either way causes a type error. – Caleb Stanford May 27 '20 at 02:26