elegant find sub-list in list

I know this question is 5 months old and already “accepted”, but googling a very similar problem brought me to this question and all the answers seem to have a couple of rather significant problems, plus I’m bored and want to try my hand at a SO answer, so I’m just going to rattle off what I’ve found.

The first part of the question, as I understand it, is pretty trivial: just return the original list with all the elements not in the “pattern” filtered out. Following that thinking, the first code I thought of used the filter() function:

def subfinder(mylist, pattern):
    return list(filter(lambda x: x in pattern, mylist))

I would say that this solution is definitely more succinct than the original solution, but it’s not any faster, or at least not appreciably, and I try to avoid lambda expressions if there’s not a very good reason for using them. In fact, the best solution I could come up with involved a simple list comprehension:

def subfinder(mylist, pattern):
    pattern = set(pattern)
    return [x for x in mylist if x in pattern]

This solution is both more elegant and significantly faster than the original: the comprehension is about 120% faster than the original, while casting the pattern into a set first bumps that up to a whopping 320% faster in my tests.

Now for the bonus: I’ll just jump right into it, my solution is as follows:

def subfinder(mylist, pattern):
    matches = []
    for i in range(len(mylist)):
        if mylist[i] == pattern[0] and mylist[i:i+len(pattern)] == pattern:
            matches.append(pattern)
    return matches

This is a variation of Steven Rumbalski’s “inefficient one liner”, that, with the addition of the “mylist[i] == pattern[0]” check and thanks to python’s short-circuit evaluation, is significantly faster than both the original statement and the itertools version (and every other offered solution as far as I can tell) and it even supports overlapping patterns. So there you go.

Leave a Comment