Find the common element between two lists in python

In this article we shall see how to find the elements which are common in both the lists in python. This can be easily done using one of the following two approaches.

  1. Looping
  2. Set intersection

Let us look at the above methods one by one with an example for each.

Looping

This is a traditional method which will be easier to understand for everyone. In this method we will iterate any one of the list, get each element and check if the element exists in the other list.

Let us look at this method with an example.

list1 = [1, 2, 4, 5]
list2 = [6, 8, 4, 2]

for numbers in list1:
    if numbers in list2:
        print(numbers)

The output of the above code is,

2
4

2 and 4 exists in both the lists.

Set intersection

The next method is by set intersection. Let us take a quick recap of what set intersection is.

What is set intersection?

In mathematics, the intersection of two sets A and B, denoted by A ∩ B, is the set containing all elements of A that also belong to B (or equivalently, all elements of B that also belong to A).

Intersection | Math Goodies
set intersection

Set intersection is nothing but finding the elements which are common to both the sets. This is what we want also.

But intersection can be performed between two sets only. So we have to typecast our list to set first in order to find the intersection.

Syntax

set1 & set2
set1.intersection(set2)

we can use either & operator to find the intersection or the intersection() method from the set data type.

Example

Let us look at an example to find the common elements between two lists by using set intersection.

list1 = [1, 2, 4, 5]
list2 = [6, 8, 4, 2]

print(set(list1) & set(list2))
print(set(list1).intersection(set(list2)))

Note that I am converting the lists to set before performing the intersection operations. The output of the above code is,

{2, 4}
{2, 4}

The result is also in set. You can typecast this to a list or iterate the set and print the values.

Conclusion

Hope this article is helpful. Follow this blog for your daily dose of python.

Happy coding!