Multiple 'In' operator in python

515 Views Asked by At
arr = [1, True, 'a', 2]
print('a' in arr in arr) # False

Can you explain me why this code will output 'False'?

The question is closed.

Answer from @KlausD.: Actually it is a comparison operator chaining and will be interpreted as ('a' in arr) and (arr in arr).

3

There are 3 best solutions below

0
On

It is False because 'a' is in 'arr' but 'arr' is not in 'arr'.

Meaning 'arr' can't be in itself.

4
On

I believe this is what you are trying to do:

arr = [1, True, 'a', 2]
print( 'a' in arr)

Output:

True

Or this:

arr = [1, True, 'a', 2]
print(bool(['a' in arr]) in arr)

Output:

True
4
On
  1. print('a' in arr in arr) // False is interpeted as print('a' in arr in arr) // 0 which throws ZeroDivisionError: integer division or modulo by zero error. If you meant to comment out the False, do it using "#", not "//" (e.g. print('a' in arr in arr) # False)
  2. 'a' in arr in arr is read from right to left[1]: check if arr in arr (False), and then check if 'a' in False (False)
  3. Using @Klaus D's helpful comment - print('a' in arr in arr) is evaluated as print(('a' in arr) and (arr in arr)) due to operator chaining. This, in turn is processed into print(True and False) -> print(False)

To check if 'a' is in arr, just check print('a' in arr) # prints True

[1] Well, not exactly. As can seen from [ In which order is an if statement evaluated in Python ], the evaluation is right to left ,so this is what actually happens: (1) check if 'a' is in "something". (2) evaluate this "something" by checking if arr in arr. (3) use the reault of said something (which is False as sadly, arr isn't a member of itslef) and check if 'a' is inside that (meaning, check if 'a' in True, which again, is False[1]