This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: Unexpected behavior of operator "in"
Type: behavior Stage: resolved
Components: Versions: Python 3.5, Python 2.7
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ammar2, mcara, tim.peters
Priority: normal Keywords:

Created on 2017-07-19 05:28 by mcara, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (6)
msg298633 - (view) Author: Mihai Cara (mcara) Date: 2017-07-19 05:28
Unexpected behavior of operator "in" when checking if a list/tuple/etc. contains a value:
>>> 1 in [1] is True
>>> (1 in [1]) is True

Is this a bug? If not, please explain why first variant return False.
msg298634 - (view) Author: Ammar Askar (ammar2) * (Python committer) Date: 2017-07-19 05:34
Check out this section of the documentation, notably this part:

"Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature"

Chaining lets you write stuff like this:

>>> x = 1
>>> 0 < x < 2

And since membership tests and identity tests are chained, the code you posted above essentially turns into:

(1 in [1]) and ([1] is True)

The former part of that expression is True but the latter is false.
msg298635 - (view) Author: Ammar Askar (ammar2) * (Python committer) Date: 2017-07-19 05:34
Sorry, forgot the actual link.
msg298636 - (view) Author: Tim Peters (tim.peters) * (Python committer) Date: 2017-07-19 05:35
Not a bug.  For an explanation, I just answered a very similar question on StackOverflow:
msg298678 - (view) Author: Mihai Cara (mcara) Date: 2017-07-19 14:18
Thank you! It was my fault: I was not expecting `in` to be a comparison operator.
msg298680 - (view) Author: Mihai Cara (mcara) Date: 2017-07-19 14:23
I am sure that some time ago I read that `in` is a comparison operator but I forgot it and I was thinking that (x in y) would be equivalent to (replaced with) the return value of y.__contains__(x).
Date User Action Args
2022-04-11 14:58:49adminsetgithub: 75148
2017-07-19 14:23:42mcarasetmessages: + msg298680
2017-07-19 14:18:04mcarasetmessages: + msg298678
2017-07-19 05:35:50tim.peterssetnosy: + tim.peters
messages: + msg298636
2017-07-19 05:34:56ammar2setmessages: + msg298635
2017-07-19 05:34:31ammar2setstatus: open -> closed

nosy: + ammar2
messages: + msg298634

resolution: not a bug
stage: resolved
2017-07-19 05:28:37mcaracreate