+ 3
in operator python
Hello dear coders, Could you please explain why the following code outputs False: a = [1, True, 'a', 2] print('a' in a in a)
5 Answers
+ 8
Ruslan Guliyev
Intuitively, we would expect something like this:
('a' in a in a)
--> (('a' in a) in a)
--> (True in a)
--> True
But as you noticed, ('a' in a in a) returns False instead. This is due to the operator chaining feature of python. https://docs.python.org/3.8/reference/expressions.html#comparisons
Some operators like `in`, `is`, `<`, etc are treated differently when chained together. For example, (3 < x < 5) is evaluated as ((3 < x) and (x < 5)). So this is how python actually evaluates your code:
('a' in a in a)
--> (('a' in a) and (a in a))
--> (True and False)
--> False
Hope this helps :)
+ 4
I could possibly be wrong, but as I understand it, chained operators go like there's a logical AND in between
So ...
'a' in a in a
May be equivalent to
'a' in a AND a in a
True AND False
With a final result of False
Just a thought : )
+ 1
Don't know much about inner workings of python, kind of just got into it.
However it seems like the in operator evaluations need precedence. I c/p your code and put print( ('a' in a) in a) and it outputs true.
Not sure if this necessarily gives you the answer you are looking for, but hope it helps at least
+ 1
So with what others said, guess it has to do less with precedence than using () to make it evaluate first in operator separately, rather than looking at the whole line
As in below works as it outputs true:
b = [5, 1, True, 'a', 2, False ]
print(('b' in b) in b)
('b' in b) == False
(False in b) == True
Output: True
+ 1