Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python operator precedence of in and comparison

Tags:

python

The following comparisons produce True:

>>> '1' in '11'
True
>>> ('1' in '11') == True
True

And with the parentheses the other way, I get a TypeError:

>>> '1' in ('11' == True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable

So how do I get False with no parentheses?

>>> '1' in '11' == True
False
like image 872
nobody Avatar asked Sep 20 '11 03:09

nobody


People also ask

How does Python compare operators to precedence?

Almost all the operators have left-to-right associativity. For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluated first. Note: Exponent operator ** has right-to-left associativity in Python.

Do all comparison operators have the same precedence in Python?

All comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Thus "==" and "<" have the same priority, why would the first expression in the following evaluate to True , different from the 2nd expression?

Which has higher precedence or in Python?

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want.

What is the order of precedence in Python in Python?

Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /, Addition +, Subtraction -.


3 Answers

The Python manual says in and == are of equal precedence. Thus, they're evaluated from left to right by default, but there's also chaining to consider. The expression you put above ('1' in '11' == True) is actually being evaluated as...

('1' in '11') and ('11' == True)

which of course is False. If you don't know what chaining is, it's what allows you to do something like...

if 0 < a < 1:

in Python, and have that mean what you expect ("a is greater than 0 but less than 1").

like image 181
Amber Avatar answered Nov 15 '22 19:11

Amber


It has nothing to do with precedence. In Python relational operators chain, and containment is considered a relational operator. Therefore:

'1' in '11' == True

is the same as:

('1' in '11') and ('11' == True)

which is false since True is not equal to "11".

like image 33
Ignacio Vazquez-Abrams Avatar answered Nov 15 '22 19:11

Ignacio Vazquez-Abrams


Chaining allows you to write x < y < z, and mean x < y and y < z. Look at this interaction:

>>> (False == True) == False
True
>>> False == (True == False)
True
>>> False == True == False
False
>>>

So in your example, '1' in '11' == True is equivalent to ('1' in '11') and ('11' == True)

like image 36
Roshan Mathews Avatar answered Nov 15 '22 20:11

Roshan Mathews