1

If this returns true,

>>> "en" in "english"
True

Why doesn't this?

>>> [1,2] in [1,2,3,4]
False
Henlo Wald
  • 37
  • 6
  • The `in` operation on strings searches for substrings. The `in` operation on most other sequences and collections matches a single element. – Barmar Jul 14 '21 at 16:18
  • @ggorlen So why does it work differently for strings? Is there any similar way to emulate this behavior with strings, since both are sequences – Henlo Wald Jul 14 '21 at 16:19
  • `"en" in list("english")` or `"en" in iter("english")` will behave like the latter, matching only elements of the iterable which is the string. – user2390182 Jul 14 '21 at 16:21
  • @HenloWald you can write your own search function that implements the behavior you expect. – ggorlen Jul 14 '21 at 16:23

2 Answers2

3

Strings and lists are simply different. a in b is implemented by b.__contains__(a). __contains__ is defined on a class-by-class basis.

When b is a str, str.__contains__(b, a) returns true if a is a substring of b.

When b is a list, list.__contains__(b, a) returns true if b is an element of a.

In order to check if a list a is a subsequence of a list b, you could try something like

any(a == b[i:i+len(a)] for i, _ in enumerate(b[:-len(a)+1]))
chepner
  • 497,756
  • 71
  • 530
  • 681
  • So I'll need my own manual implementation to search for multiple elements in other sequences...eg. a for loop that checks for all elements until an element is not found to return False, else True...there is no inbuilt method/operator to emulate the same behavior – Henlo Wald Jul 14 '21 at 16:21
-2

This will give you true: >>>1 and 2 in [1,2,3,4] But [1,2] means that you are checking for the list [1,2] in the list [1,2,3,4] which is not there. It would be true if your list was [[1,2],3,4].

>>> [1,2] in [[1,2],3,4]
True
sam2611
  • 455
  • 5
  • 15