# Why does the code result in such output???

Hi everyone!!! In one of the challenges I get stuck on some particular code which yields the output I can't explain to myself. So the following code yields "False": arr = [1, True, 'a', 2] print('a' in arr in arr) Why does it happen??? Furthermore the following yields "True": print(('a' in arr) in arr) and the following raises "TypeError": print('a' in (arr in arr)) How can it be???

9/25/2021 2:49:55 PM

Alexander Sergeev10 Answers

New AnswerI can't explain how the first expression evaluation worked. But for the second and third, I guess the use of parentheses plays a role in changing the evaluation priority. Second expression: ( ( 'a' in arr ) in arr ) evaluated as ( ( True ) in arr ) and this yields True because <arr> has a member whose value is True. Third expression: ( 'a' in ( arr in arr ) ) is evaluated as ( 'a' in ( False ) ) and this is not possible because the `in` operator requires an iterable for its RHS operand. But here the RHS operand is a boolean ( False ). I look forward to learn how the first expression is evaluated.

I can't say this with 100% assurance But after running some test I think both "in" operater are executed simultaneously Like: 'a' in arr in arr =('a' in arr) and (arr in arr) Because only way to get result of True in a statement like a in b in c there should be (a in b) == (b in c) == True Hope It Helps You

The explanation given by Hacker Badshah makes sense to me. It would mean that a in b in c works similar to a < b < c as both would be treated like two expressions connected with and.

Hacker Badshah seems to be right: https://stackoverflow.com/questions/12660870/associativity-of-in-in-python

Hacker Badshah and Simon Sauter are right! I tried appending <arr> to itself, and the first expression evaluates to True ... arr = [1, True, 'a', 2] print('a' in arr in arr) # output False arr.append( arr ) print( 'a' in arr in arr ) # output True All this time I thought only logical and arithmetic operators are chainable. Now I see that the `in` operator is also chainable LMAO :D

Simon Sauter Gave very good example a < b < c works exactly similar to this So, Alexander Sergeev we cracked the hard nutðŸ˜‚

So as I :-) The second and third expressions are explainable but the first is a hard nut!

You are right, guys! Thanks a lot!!! Indeed, I've found in the Python Docs that "in" is a sort of comparisons and therefore it's chainable. So the following two lines of code give the same result "False": print('a' in arr and arr in arr) print('a' in arr in arr) Moreover the next line gives you "False" too: print(arr in arr) But the next one raises a TypeError: print('a' in (arr in arr)) because, assuming that (arr in arr) = False, we have equivalence: print('a' in (arr in arr)) = print('a' in False) but "in" operator is only for iterables, therefore we have a TypeError. Again, thanks a lot to everyone!!!