The Python Oracle

How can I compare two lists in python and return matches

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands

--

Chapters
00:00 How Can I Compare Two Lists In Python And Return Matches
00:14 Accepted Answer Score 693
00:36 Answer 2 Score 563
00:46 Answer 3 Score 139
01:38 Answer 4 Score 92
01:49 Answer 5 Score 30
01:55 Thank you

--

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

--

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