Why does "not(True) in [False, True]" return False?
--
Track title: CC F Haydns String Quartet No 53 in D
--
Chapters
00:00 Question
00:40 Accepted answer (Score 742)
01:18 Answer 2 (Score 77)
02:27 Answer 3 (Score 37)
02:45 Answer 4 (Score 34)
03:18 Thank you
--
Full question
https://stackoverflow.com/questions/3142...
Accepted answer links:
[2.x]: https://docs.python.org/2/reference/expr...
[3.x]: https://docs.python.org/3/reference/expr...
Answer 4 links:
[operator precedence]: https://docs.python.org/2/reference/expr...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #operatorprecedence #comparisonoperators
#avk47
ACCEPTED ANSWER
Score 750
Operator precedence 2.x, 3.x. The precedence of not is lower than that of in. So it is equivalent to:
>>> not ((True) in [False, True])
False
This is what you want:
>>> (not True) in [False, True]
True
As @Ben points out: It's recommended to never write not(True), prefer not True. The former makes it look like a function call, while not is an operator, not a function.
ANSWER 2
Score 37
Operator precedence. in binds more tightly than not, so your expression is equivalent to not((True) in [False, True]).
ANSWER 3
Score 34
It's all about operator precedence (in is stronger than not). But it can be easily corrected by adding parentheses at the right place:
(not(True)) in [False, True] # prints true
writing:
not(True) in [False, True]
is the same like:
not((True) in [False, True])
which looks if True is in the list and returns the "not" of the result.
ANSWER 4
Score 14
It is evaluating as not True in [False, True], which returns False because True is in [False, True]
If you try
>>>(not(True)) in [False, True]
True
You get the expected result.