Unexpected result with `in` operator chaining

后端 未结 1 678
时光说笑
时光说笑 2020-12-06 23:14

As far as I know, the in operator in Python can\'t be chained or at least I couldn\'t find any info on it, here is my problem

Here is the code



        
相关标签:
1条回答
  • 2020-12-06 23:49

    The premise is false; the in operator can be chained. See Comparisons in the docs:

    comp_operator ::=  "<" | ">" | "==" | ">=" | "<=" | "!="
                       | "is" ["not"] | ["not"] "in"
    

    So, just as with any other chained comparison, a in b in c is equivalent to (a in b) and (b in c) (except that b is only evaluated once.

    The reason 'a' in arr in arr is false is that arr in arr is false. The only time x in x is true is if x is type that does substring comparisons for __contains__ (like str or bytes), or if it's a container that actually contains itself (like lst = []; lst.append(lst)).

    0 讨论(0)
提交回复
热议问题