0

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?

Sushant Kumar
  • 435
  • 7
  • 24
  • Try `print("without you".split())` – Plouff Mar 24 '16 at 14:00
  • Use [**`any`**](https://docs.python.org/2/library/functions.html#any), if you want to see if `'yo'` is in a string in a list: `any('yo' in word for word in 'without you'.split())` – Peter Wood Mar 24 '16 at 14:01
  • Possible duplicate of [Check if a Python list item contains a string inside another string](http://stackoverflow.com/questions/4843158/check-if-a-python-list-item-contains-a-string-inside-another-string) – Peter Wood Mar 24 '16 at 14:04
  • did you look at what `"without you".split()` returns? – Padraic Cunningham Mar 24 '16 at 14:13

1 Answers1

5

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

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328