Since you are comparing consecutive indexes and think that lst and seq are of the same type, you can use slicing:
def sequence_in_list(seq, lst): m, n = len(lst), len(seq) for i in xrange(m): for j in xrange(n): if lst[i:i+3] == seq[j:j+3]: return lst[i+3]
If the sequences have a different look, you must convert them to a general type before performing a comparison (for example, lst[i:i+3] == list(seq[j:j+3]) will work if seq is a string and lst - list).
Alternatively, if the sequences do not support slicing, you can use the built-in all to check for additional conditions:
def sequence_in_list(seq, lst): m, n = len(lst), len(seq) for i in xrange(m): for j in xrange(n): if all(lst[i+k] == seq[j+k] for k in range(3)): return lst[i+3]
If you want to extend the check of more than 10 indexes instead of 3, just change range(3) to range(10) .
Side note: your source code will raise an IndexError at some point, since you will get access to list[i+1] , where i may be len(list) - 1 . The above code does not cause errors, since slicing can give a shorter cut than the index difference, meainig, that seq[j:j+3] can have less than 3 elements. If this is a problem, you should adjust the indexes you are iterating over.
One final note: do not use the name list , as it obscures the built-in name.
source share