JuniorCodeOccasionalNot answered yet
What do these chained comparisons print?
Predict all three lines.
print(1 < 2 < 3) # (1)
print(3 > 2 == 2) # (2)
print(False == False in [False]) # (3)
Determine the output and explain.
All three print True. Python chains comparisons with an implicit and: (1) is 1 < 2 and 2 < 3; (2) is 3 > 2 and 2 == 2; (3) is (False == False) and (False in [False]) → True and True. The third surprises people because == and in chain together.
- ✗Reading
a < b < cas(a < b) < cinstead of an implicitand - ✗Not realizing
==andinchain together in one expression - ✗Expecting a chained comparison to return an operand rather than a bool
- →How does Python evaluate the middle operand of a chain exactly once?
- →Why is
False == False in [False]not(False == False) in [False]?