Categories
Python Answers

How to find the common elements between 2 lists with Python?

Spread the love

Sometimes, we want to find the common elements between 2 lists with Python.

In this article, we’ll look at how to find the common elements between 2 lists with Python.

How to find the common elements between 2 lists with Python?

To find the common elements between 2 lists with Python, we can convert the first list to a set and use the set’s intersection method.

For instance, we write:

list1 = [1, 2, 3, 4, 5, 6]
list2 = [3, 5, 7, 9]
intersection = list(set(list1).intersection(list2))
print(intersection)

We have 2 lists list1 and list2 and we want to get the intersection between them.

To do this, we call set with list1 to convert it to a set.

Then we can call intersection on it with list2 to return a set that has values from both lists.

Finally, we call list to return a list by converting it from the intersection set.

Therefore, intersection is [3, 5].

Conclusion

To find the common elements between 2 lists with Python, we can convert the first list to a set and use the set’s intersection method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *