I've used "in" operator in different scenarios below. One is directly on a string and another on a list of strings.
>>> "yo" in "without you"
True
>>> "yo" in "without you".split()
False
Why is the output different?
I've used "in" operator in different scenarios below. One is directly on a string and another on a list of strings.
>>> "yo" in "without you"
True
>>> "yo" in "without you".split()
False
Why is the output different?
For strings, the in
operator returns true if the left-hand-side is a substring of the right-hand-side.
So "yo" in "without you"
asks: Does the substring "yo"
appear anywhere in the string "without you"
? Yes.
For sequences (like lists), the in
operator returns true if the left-hand-side is equal to any element in the right-hand-side.
"without you".split()
will return ["without", "you"]
.
So "yo" in ["without", "you"]
asks: Does"yo"
equal one of those two strings? No.
See also
__contains__