Check for presence of a sliced list in Python

Let’s get a bit functional, shall we? 🙂

def contains_sublist(lst, sublst):
    n = len(sublst)
    return any((sublst == lst[i:i+n]) for i in xrange(len(lst)-n+1))

Note that any() will stop on first match of sublst within lst – or fail if there is no match, after O(m*n) ops

Leave a Comment