Check for presence of a sliced list in Python

Viewed 27507

I want to write a function that determines if a sublist exists in a larger list.

list1 = [1,0,1,1,1,0,0]
list2 = [1,0,1,0,1,0,1]

#Should return true
sublistExists(list1, [1,1,1])

#Should return false
sublistExists(list2, [1,1,1])

Is there a Python function that can do this?

12 Answers

My favourite simple solution is following (however, its brutal-force, so i dont recommend it on huge data):

>>> l1 = ['z','a','b','c']
>>> l2 = ['a','b']
>>>any(l1[i:i+len(l2)] == l2 for i in range(len(l1)))
True

This code above actually creates all possible slices of l1 with length of l2, and sequentially compares them with l2.

Detailed explanation

Read this explanation only if you dont understand how it works (and you want to know it), otherwise there is no need to read it

Firstly, this is how you can iterate over indexes of l1 items:

>>> [i for i in range(len(l1))]
[0, 1, 2, 3]

So, because i is representing index of item in l1, you can use it to show that actuall item, instead of index number:

>>> [l1[i] for i in range(len(l1))]
['z', 'a', 'b', 'c']

Then create slices (something like subselection of items from list) from l1 with length of2:

>>> [l1[i:i+len(l2)] for i in range(len(l1))]
[['z', 'a'], ['a', 'b'], ['b', 'c'], ['c']] #last one is shorter, because there is no next item.

Now you can compare each slice with l2 and you see that second one matched:

>>> [l1[i:i+len(l2)] == l2 for i in range(len(l1))]
[False, True, False, False] #notice that the second one is that matching one

Finally, with function named any, you can check if at least one of booleans is True:

>>> any(l1[i:i+len(l2)] == l2 for i in range(len(l1)))
True

I know this might not be quite relevant to the original question but it might be very elegant 1 line solution to someone else if the sequence of items in both lists doesn't matter. The result below will show True if List1 elements are in List2 (regardless of order). If the order matters then don't use this solution.

List1 = [10, 20, 30]
List2 = [10, 20, 30, 40]
result = set(List1).intersection(set(List2)) == set(List1)
print(result)

Output

True
Related