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
Quick way:
list(set(a).intersection(set(b)))
Can use itertools.product too.
>>> common_elements=[]
>>> for i in list(itertools.product(a,b)):
... if i[0] == i[1]:
... common_elements.append(i[0])
Use set.intersection(), it's fast and readable.
>>> set(a).intersection(b)
set([5])
another a bit more functional way to check list equality for list 1 (lst1) and list 2 (lst2) where objects have depth one and which keeps the order is:
all(i == j for i, j in zip(lst1, lst2))
If you want a boolean value:
>>> a = [1, 2, 3, 4, 5]
>>> b = [9, 8, 7, 6, 5]
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b)
False
>>> a = [3,1,2]
>>> b = [1,2,3]
>>> set(b) == set(a) & set(b) and set(a) == set(a) & set(b)
True
You can use
def returnMatches(a,b):
return list(set(a) & set(b))