Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a python "in" statement evaluate this way? [duplicate]

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!

like image 940
Keegan Conlee Avatar asked May 27 '20 02:05

Keegan Conlee


People also ask

What is duplicate in Python?

What are duplicates in a list? If an integer or string or any items in a list are repeated more than one time, they are duplicates.

What will happen if a set has duplicate entries Python?

Sets cannot contain duplicates. Duplicates are discarded when initializing a set. If adding an element to a set, and that element is already contained in the set, then the set will not change.

How do you use duplicates in Python?

Pandas DataFrame duplicated() MethodThe duplicated() method returns a Series with True and False values that describe which rows in the DataFrame are duplicated and not.


Video Answer


1 Answers

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.

like image 189
Mark Ransom Avatar answered Nov 10 '22 16:11

Mark Ransom