'Comparing lists with order

I wish to compare lists and output the similar matches that following each other in the same order.

list1 = ['a','b', 'b', 'c']
list2 = ['b', 'a', 'a', 'c']

# With the intersection() command, the output is the matching strings regardless of the order of the strings:
set(list1).intersection(set(list2))
{'a', 'b', 'c'}

# I wish to output only the strings that are following each other in the two lists. Here the two answers could be :
{'a', 'c'}
# or
{'b', 'c'}

Would you know any tricks to do it?



Solution 1:[1]

I think I have found an answer, but still have some issues with duplicated values in the lists.

list = []

len1 = len(list1) 

len2 = len(list2)

start_range = 0 for f1 in range(len1) :
    for f2 in range(start_range, len2) :
        if list1[f1] == list2[f2]:
            list.append(list1[f1]);
            start_range = f2;
            break;  
 print(list)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1