TransWikia.com

What is the precedence of the "in" operator?

Stack Overflow Asked by KrisH Jodu on November 12, 2021

Today I encountered a difficult situation in this Python program:

a = [False, True]
x = True in a in a
y = True in a in [a]
z = True in a in (a)
print(x, y, z)

The output of this code is

False True False

How is it possible?

Let’s test for x here:

x = True in a in a

True in [False, True] is True, and again True in [False, True] is True.

So x should be True. But when I run the program it says False.

And now let’s come from right to left:

x = True in a in a

[False, True] in [False, True] is False, so now True in False might be a type error or some other error.

Could you please explain this?

One Answer

Python chains certain operators, including in.

This:

True in a in [a]

means

(True in a) and (a in [a])

so if a is equal to [False,True], then the expression is true.


The other versions:

True in a in a
True in a in (a)

are equivalent to each other. Putting parentheses around (a) doesn't change its type or its value.

Both mean (True in a) and (a in a), so unless a contains itself, they are false.

Answered by khelwood on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP