I recently discovered that the following returns True
:
'a' in 'ab' in 'abc'
I'm aware of the python comparison chaining such as a < b < c
, but I can't see anything in the docs about this being legal.
Is this an accidental feature in the implementation of CPython, or is this behaviour specified?
This is fully specified behaviour, not an accidental feature. Operator chaining is defined in the Comparison operators section:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
, except thaty
is evaluated only once (but in both casesz
is not evaluated at all whenx < y
is found to be false).
in
is one of the comparison operators; from the same section:
comp_operator ::= "<" | ">" | "==" | ">=" | "<=" | "<>" | "!=" | "is" ["not"] | ["not"] "in"
No exceptions are made for combinations that may not make much sense.
The specific expression you used as an example is thus executed as 'a' in 'ab' and 'ab' in 'abc'
, with the 'ab'
literal only being executed (loaded) once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With