Comparing two lists in Python

If the two lists are the same length, you can do a side-by-side iteration, like so:

list_common = []
for a, b in zip(list_a, list_b):
    if a == b:
        list_common.append(a)

Use set intersection 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 into a string.

--

For your example/comment below, this will preserve order (inspired by comment from @DSM)

' '.join([j for j, m in zip(john.split(), mary.split()) if j==m])
'I love yellow and'

For a case where the list aren't the same length, with the result as specified 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']