Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "('a' in arr) in arr" != "'a' in arr in arr"? [duplicate]

Why is ('a' in arr) in arr != 'a' in arr in arr?

arr = [1, True, 'a', 2]
print(('a' in arr) in arr)  # -> True
print('a' in arr in arr)  # -> False
like image 251
Max Sh Avatar asked Dec 23 '22 19:12

Max Sh


1 Answers

Section 6.10 of the Python language reference discusses comparison operators and comparison chaining. in is considered a comparison operator, and so behaves the same as <, etc. Without parentheses for explicit grouping, x OP1 y OP2 zis equivalent to x OP1 y and y OP2 z for any two comparison operators.

This means that

'a' in arr in arr

without parentheses, is equivalent to

'a' in arr and arr in arr

arr is not an element of itself, so the expression is False.

Parentheses disable chaining, so

('a' in arr) in arr

is evaluated like any other nested expression. 'a' in arr is evaluated first to the value True, then True in arr is evaluated to also produce True.

like image 91
chepner Avatar answered Jan 02 '23 07:01

chepner