Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
283 views
in Technique[技术] by (71.8m points)

python - Unexpected result with `in` operator chaining

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

arr = [1, True, 'a', 2]
print('a' in arr in arr)  # prints False
print(('a' in arr) in arr)  # prints True

What I don't understand is the first print, I know in the second the first in returns True and then it check if True is in arr, but what about the first one? Does it check if 'a' is in arr and then if arr is in arr?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...