Sometimes, we want to compare two lists and return matches with Python.
In this article, we’ll look at how to compare two lists and return matches with Python.
How to compare two lists and return matches with Python?
To compare two lists and return matches with Python, we can use the set’s intersection
method.
For instance, we write:
a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
intersection = set(a).intersection(b)
print(list(intersection))
We have 2 lists a
and b
that we want to get the intersection between.
To do this, we convert a
to a set with set
.
Then we call intersection with
band assign the intersection of
aand
bto
intersection`.
And finally, we call list
with intersection
to convert it back to a list.
Therefore, [5]
is printed.
Conclusion
To compare two lists and return matches with Python, we can use the set’s intersection
method.