In this article, we will understand how to find common elements present in two given lists if they exist, in Python using Python sets. We will be doing so by creating Python set objects using the given lists and then comparing them using the &
operator and using the set intersection()
method.
1. Python Set with &
Operator
A Set never contains any duplicate value, this means, even if duplicates are supplied to it, they are safely ignored. So, we will be creating set objects using the lists given, and then we will find out the common elements present in the lists.
Here is the code for the function we have created in python, to which you can provide two lists and it will print the common elements. You can even use it to return back the common elements rather than printing them.
def common_elements(list_1, list_2):
a_set = set(list_1)
b_set = set(list_2)
if (a_set & b_set):
print(a_set & b_set)
else:
print("No common elements between the two lists")
Below we have the running code example for this:
2. Using Python Set intersection()
method
Instead of directly using a set, we can use the intersection()
method of Python set. This method is specifically meant to extract common elements present among two set objects. In the code below, we have defined a function which takes two lists, creates set object using that list and then uses the intersection()
method to find out common elements present in the given lists.
def common_elements(list_1, list_2):
a_set = set(list_1)
b_set = set(list_2)
if len(a_set.intersection(b_set)) > 0:
print (list(a_set.intersection(b_set)))
else:
print("No common elements between the two lists")
Below we have the running code example for this:
Conclusion
In this article, we saw how to extract the common elements that are present in two lists in Python. Let us know how you would approach this problem in the comment section below.
You may also like: