Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I compare two lists in python and return matches

Tags:

python

list

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.

like image 799
tehryan Avatar asked Sep 07 '09 11:09

tehryan


People also ask

How can I compare two lists in Python and return differences?

The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .


1 Answers

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).

like image 177
SilentGhost Avatar answered Oct 06 '22 11:10

SilentGhost