python: compare two lists and return matches in order

list, python, set

Solution

Convert `b` to a set and then loop over `a`'s items and check if they exist in that set:

>>> s = set(b)
>>> [x for x in a if x in s]
['a', 'd']

Problem

I have two lists of unequal length and I would like to compare and pull matched values in the order from the first list, so a in this example. ``` a = ['a','s','d','f'] b = ['e','d','y','a','t','v'] ``` expected output: ``` ['a','d'] ``` I was doing it like this but I forgot that set doesnt retain the order! how can I edit my code below to retain the order. ``` set(a).intersection(b) ``` Linked to this How can I compare two lists in python and return matches

Original source

Related problems