tags:

views:

3456

answers:

10

I want to take two lists and find the values that appear in both.

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]

returnMatches(a, b)

would return [5], for instance.

+14  A: 

Not the most efficient one, but by far the most obvious way to do it is:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
{5}

if order is significant you can do it with list comprehensions like this:

>>> [i for i, j in zip(a, b) if i == j]
[5]

(only works for equal-sized lists, which order-significance implies).

SilentGhost
+1  A: 

The easiest way to do that is to use sets:

>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(a) & set(b)
set([5])
Greg Hewgill
+11  A: 

Use set.intersection(..).

aa = set(a)
print aa.intersection(b)
# => set([5])
This answer has good algorithmic performance, as only one of the lists (shorter should be preferred) is turned into a set for quick lookup, and the other list is traversed looking up its items in the set.
kaizer.se
+1  A: 

Quick way:

list(set(a).intersection(set(b)))
DisplacedAussie
+1  A: 

Do you want duplicates? If not maybe you should use sets instead:


>>> set([1, 2, 3, 4, 5]).intersection(set([9, 8, 7, 6, 5]))
set([5])
Timothy Pratley
If you really want lists,http://www.java2s.com/Code/Python/List/Functiontointersecttwolists.htm>>> intersect([1, 2, 3, 4, 5], [9, 8, 7, 6, 5])[5]
Timothy Pratley
+3  A: 

You can use

def returnMatches(a,b):
       return list(set(a) & set(b))
Prabhu
A: 

how to get the unmatched entries?

surab
This should be a different question.
TokenMacGuy
+1  A: 

s = ['a','b','c']
f = ['a','b','d','c']
ss= set(s)
fs =set(f)
print ss.intersection(fs)
set(['a', 'c', 'b'])
print ss.union(fs)
set(['a', 'c', 'b', 'd'])
print ss.union(fs) - ss.intersection(fs)
set(['d'])

setz
A: 

Setz' answer seems complicated. Perhaps you would rather do

set(f) - set(s)

:)

Prufrock
+1  A: 

I prefer the set based answers, but here's one that works anyway

[x for x in a if x in b]
TokenMacGuy