The Python Oracle

How can I compare two lists in python and return matches

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Track title: CC D Schuberts Piano Sonata D 850 in D

--

Chapters
00:00 Question
00:26 Accepted answer (Score 664)
00:54 Answer 2 (Score 542)
01:09 Answer 3 (Score 136)
02:25 Answer 4 (Score 86)
02:39 Thank you

--

Full question
https://stackoverflow.com/questions/1388...

Answer 1 links:
[set.intersection()]: http://docs.python.org/library/stdtypes....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ACCEPTED ANSWER

Score 694


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




ANSWER 2

Score 564


Use set.intersection(), it's fast and readable.

>>> set(a).intersection(b)
set([5])



ANSWER 3

Score 92


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

[x for x in a if x in b]



ANSWER 4

Score 30


Quick way:

list(set(a).intersection(set(b)))