finding all sublists of list2 that are identical to list1

Klaus Neuner klaus_neuner82 at yahoo.de
Mon Feb 9 09:59:35 EST 2004


Hello, 

the function given below returns all indexes of list2 where a sublist
of list2 that is identical to list1 begins.

As I will need this function quite often, I would like to know if more
experienced programmers would agree with the way I defined the
function:

- Is there a more efficient way to do it? (Apart from building
automata.)
- Is there a more elegant/Pythonic way to write the function?

Klaus


def sublist(list1, list2):
    if list1 == list2:
        return [0]
    elif len(list1) > len(list2):
        return []
    else:
        result = []
        shift = 0
        i = 0
        while shift <= len(list2)-len(list1):
            if list1[i] == list2[shift+i]:
                if i == len(list1)-1:
                    result.append(shift)
                    i = 0
                    shift += 1
                else:
                    i += 1
            else:
                i = 0
                shift += 1
        return result



More information about the Python-list mailing list