Issue 30965: Unexpected behavior of operator "in" (original) (raw)

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 False >>> (1 in [1]) is True 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 True 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. https://docs.python.org/3/reference/expressions.html#operator-precedence
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: https://stackoverflow.com/questions/45180899/unexpected-result-from-in-operator/45180967#45180899
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).
History
Date User Action Args
2022-04-11 14:58:49 admin set github: 75148
2017-07-19 14:23:42 mcara set messages: +
2017-07-19 14🔞04 mcara set messages: +
2017-07-19 05:35:50 tim.peters set nosy: + tim.petersmessages: +
2017-07-19 05:34:56 ammar2 set messages: +
2017-07-19 05:34:31 ammar2 set status: open -> closednosy: + ammar2messages: + resolution: not a bugstage: resolved
2017-07-19 05:28:37 mcara create