-3
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).

Matvey
  • 15
  • 3

3 Answers3

1

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

Meaning 'arr' can't be in itself.

Jamie Lindsey
  • 928
  • 14
  • 26
0

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
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19
  • you can just do `print(('a' in arr) in arr)` instead of `print(bool(['a' in arr]) in arr)` but that does not check if `'a'` is in `arr`. It check if `True` is! Change arr to `arr = ['a', 2]` and verify – CIsForCookies Nov 11 '18 at 07:21
  • Question is not clear. I am assuming he wants to get the output from 'a' in arr as True and then check if True in arr. – Sanchit Kumar Nov 11 '18 at 07:22
  • Legit. I thought OP only wants to check if `'a' in arr`. Either way, what actually being checked is if `arr in arr`, and then if 'a' is in the result :-P – CIsForCookies Nov 11 '18 at 07:26
  • `bool(['a' in arr])` is almost certainly not any part of what the questioner wanted, considering it's calling `bool` on a one-element list, and it'll return `True` no matter whether or not `'a'` is in `arr`. – user2357112 Nov 11 '18 at 08:02
0
  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]

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124