Question about operator precedence for in and !=

Question:

While writing Python code, I got a result different from what I wanted.

>>> temp = [1]
>>> 1 in temp != 2 in temp
False
>>> (1 in temp) != (2 in temp)
True
>>> ((1 in temp) != 2) in temp
True

My purpose was the second, but I wrote it like the first.

The problem has been solved, but I wonder in what order the first expression outputs False.

I wondered if it was because of the same principle as the third, but the third also outputs True.

Asked By: helpingstar

||

Answers:

I believe this is caused by operator chaining.

In Python, you can write an expression with two (or more) operators like this:

a < b < c

And Python treats this as if you wrote (a < b) and (b < c).

So Python is treating your expression

1 in temp != 2 in temp

As if you wrote:

(1 in temp) and (temp != 2) and (2 in temp)

Which is false.

Answered By: John Gordon
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.