Why the result of this code "True in [True] in [True]" is False | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 7

Why the result of this code "True in [True] in [True]" is False

I do not understand the logic so that the result of this code is FALSE, if I use parentheses to give priority then it is TRUE arr = [True] print (True in arr in arr) print ((True in arr) in arr) #output False True

15th Feb 2018, 2:43 PM
Javier I. Rivera R.
Javier I. Rivera R. - avatar
3 Answers
+ 3
Got the explanation from Stack overflow (https://stackoverflow.com/questions/25103085/chaining-is-operators). Let me summarize the contents of this answer for everyone. According to Language reference, *in* is one of comparison operators. >if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z So the expression "True in arr in arr" is equivalent to "(True in arr) and (arr in arr)" since arr in arr is false, the whole expression evaluates to false. In the second case, since we have explicitly used parentheses, the interpreter evaluated it the way we expected.
15th Feb 2018, 5:42 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar
+ 1
My way of understanding is 'substitute then execute'. You write: True in arr in arr substitute it: True in [True] in [True]. right? For clarity, it can be interpret as, True in [True] and [True] in [True] *** note 'and' between expression. So, first expression ( True in [True] ) evaluate True because ***True object*** present in list (i.e arr). Second expression ( [True] in [True] ) evaluate False because ***list containing True object*** doesn't contain in list (i.e arr). arr list only contain True object. If u want that statement true, create another list object and add [[True]] to that new list. Summary version: arr = [True] 1 in arr in arr (which will never return true). If u confuse, then substitute first. new_arr = [[True]] 1 in arr in new_arr >> True Using parenthesis is self-explanatory. Hope it helps :) sry for my english btw.
15th Feb 2018, 6:06 PM
Sylar
0
Good question! It is looking strange to me as well. I thought the additional parenthesis are irrelevant because Python documentation says all operators except exponentiation (**) are left associative. That means 'True in arr' should always get evaluated first, even if we don't enclose them with parenthesis. So I guessed, both would return the same answer. However there might be some reasoning behind the python interpreter behaving in this manner.
15th Feb 2018, 5:19 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar