6

I'm trying to figure out in what order this code runs:

print( True in [True] in [True] )
False

even though:

print( ( True in [True] ) in [True] )
True

and:

print( True in ( [True] in [True] ) )
TypeError

If the first code is neither of these two last ones, then what?

arsalan
  • 83
  • 6

2 Answers2

11

in is comparing with chaining there so

True in [True] in [True]

is equivalent to (except middle [True] is evaluated once)

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

which is

True and False

which is

False

This is all similar to

2 < 4 < 12

operation which is equivalent to (2 < 4) and (4 < 12).

1

print( True in [True] in [True] )

This is actually interpreted as - True in [True] and [True] in [True] which gives you false because it becomes - True and False

print( ( True in [True] ) in [True] )

The ( True in [True] ) is checked first, so you get True in [True] which is True.

print( True in ( [True] in [True] ) )

The second part is checked, before the first because of parenthesis which changes the order, so it becomes - True in True. And True which is a boolean, is not a iterable, so you cannot use in, and then you get TypeError

PCM
  • 2,881
  • 2
  • 8
  • 30