Find the common elements in two lists in Python

In this tutorial, We are going to learn how to find the common elements in two lists in Python.
To find the common list from two lists, we have to store the common elements in the third variable. There are various methods to find and store the common elements from two lists.

How to find the common elements in two lists in Python

To learn the various ways to find the common elements from two lists in Python. We have to make two separate lists.
We will learn all the ways with an example.

Using a function

Example 1: Make a function for both lists. If there are common elements in both the list, then it will return common elements in list c.
If both lists do not contain any common elements then it will return an empty list.

a=[2,3,4,5]
b=[3,5,7,9]

def common(a,b): 
    c = [value for value in a if value in b] 
    return c

d=common(a,b)
print(d)

Both the list have common elements 3 & 5, So it will return [3,5].

[3, 5]

Using set() function

Example 2: Using set( ) function, We can return common elements of a list in the third variable.  If both lists do not contain any common elements then it will return an empty list. You may learn more: Sets and its Methods in Python

a=[2,9,4,5]
b=[3,5,7,9]
def common(lst1, lst2): 
    return list(set(lst1) & set(lst2))
e=common(a,b)
print(e)

Both the list have common elements 9 & 5, So it will return [9,5].

Output–

[9, 5]

Find the common items from two lists using set().intersection()

Example 3- Using set( ).intersection(), We can print the list of common elements of a list, but it can not store in any of the variables.
If both lists do not contain any common elements then it will return an empty set( ).

a=[2,9,4,5]
b=[3,5,7,2]
print(set(a).intersection(b))

Both the list have common elements 2 & 5, So it will return [2,5].

Output–

{2, 5}

2 responses to “Find the common elements in two lists in Python”

  1. sagar says:

    the problem with set method is
    if l1=[2,3,2,4] and l2=[2,2,2,7]
    conveerting these two to sets and tai
    king interstion will give {2} when infact the elements common for the lists are [2,2]

    • Sushanth Gopal says:

      #You can use this method right
      l1=[2,3,2,4]
      l2=[2,2,2,7]
      c = [value for value in l1 if value in l2]
      print(c)

Leave a Reply

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