7

In python, it's possible to use the is keyword to check for contains, e.g.

>>> 3 in [1,2,3,4,5]
True

But this doesn't yield the same output if it's checking whether a list of a single integer is inside the reference list [1,2,3,4,5]:

>>> [3] in [1,2,3,4,5]
False

Also, checking a subsequence in the reference list cannot be achieved with:

>>> [3,4,5] in [1,2,3,4,5]
False

Is there a way to have a function that checks for subsequence such that the following returns true? e.g. a function call x_in_y():

>>> x_in_y([3,4,5], [1,2,3,4,5])
True
>>> x_in_y([3], [1,2,3,4,5])
True
>>> x_in_y(3, [1,2,3,4,5])
True
>>> x_in_y([2,3], [1,2,3,4,5])
True
>>> x_in_y([2,4], [1,2,3,4,5])
False
>>> x_in_y([1,5], [1,2,3,4,5])
False

Maybe something from itertools or operator?

(Note, the input lists can be non-unique)

alvas
  • 115,346
  • 109
  • 446
  • 738
  • 1
    i think this has been answered already. http://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list – Alex J Oct 28 '15 at 13:32

2 Answers2

8

x_in_y() can be implemented by slicing the original list and comparing the slices to the input list:

def x_in_y(query, base):
    try:
        l = len(query)
    except TypeError:
        l = 1
        query = type(base)((query,))

    for i in range(len(base)):
        if base[i:i+l] == query:
            return True
    return False

Change range to xrange if you are using Python2.

301_Moved_Permanently
  • 4,007
  • 14
  • 28
-4

Maybe something like this:

def x_in_y(search_list, my_list):
    return all([s in my_list for s in search_list])

provided the search_list is a list.

Alex
  • 41,580
  • 88
  • 260
  • 469
  • 1
    This only checks that all items in `search_list` exist individually in `my_list` - it doesn't check that they exist as a subsequence, so the `x_in_y([2,4], [1,2,3,4,5])` test incorrectly returns True. – gasman Apr 14 '19 at 21:42
  • Also: `x_in_y([1, 1, 1, 1], [1])` – Gerrit Begher Dec 03 '19 at 07:59