Use the intersection set for this:
list(set(listA) & set(listB))
gives:
['a', 'c']
Note that since we are dealing with sets, this may not preserve order:
' '.join(list(set(john.split()) & set(mary.split()))) 'I and love yellow'
using join()
to convert the resulting list to a string.
-
For your example / comment below, this will keep order (inspired by the comment from @DSM)
' '.join([j for j, m in zip(john.split(), mary.split()) if j==m]) 'I love yellow and'
In the case where the list does not have the same length, with the result indicated in the comment below:
aa = ['a', 'b', 'c'] bb = ['c', 'b', 'd', 'a'] [a for a, b in zip(aa, bb) if a==b] ['b']
source share