Why is the logical expression "1 in (1, 2, 3))" True "" False?

Why does the 1 in (1, 2, 3) == True operator return False in Python? Is operator precedence in Python ambiguous?

+5
source share
1 answer

Because of the documentation about operator priority:

Note that comparisons, membership tests, and identity tests have the same priority and have a binding function from left to right, as described in the Comparisons section.

The Comparisons section shows an example chain:

The comparison can be copied arbitrarily, for example, x < y <= z equivalent to x < y and y <= z

So:

 1 in (1, 2, 3) == True 

interpreted as:

 (1 in (1, 2, 3)) and ((1, 2, 3) == True) 

If you override this chain by adding parentheses, you get the expected behavior:

 >>> (1 in (1, 2, 3)) == True True 

Note that instead of comparing likelihood using equality with True or False you should simply use, for example. if thing: and if not thing:

+10
source

Source: https://habr.com/ru/post/1261086/


All Articles