0

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
KrisH Jodu
  • 104
  • 9

1 Answers1

6

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.

khelwood
  • 55,782
  • 14
  • 81
  • 108