I want to take two lists and find the values that appear in both.
JavaScript
x
5
1
a = [1, 2, 3, 4, 5]
2
b = [9, 8, 7, 6, 5]
3
4
returnMatches(a, b)
5
would return [5]
, for instance.
Advertisement
Answer
Not the most efficient one, but by far the most obvious way to do it is:
JavaScript
1
5
1
>>> a = [1, 2, 3, 4, 5]
2
>>> b = [9, 8, 7, 6, 5]
3
>>> set(a) & set(b)
4
{5}
5
if order is significant you can do it with list comprehensions like this:
JavaScript
1
3
1
>>> [i for i, j in zip(a, b) if i == j]
2
[5]
3
(only works for equal-sized lists, which order-significance implies).