Find Common Elements in two Lists in Python

The lists [‘apple’,’banana’,’strawberry’] and [‘orange’,’banana’] have one comment element: ‘banana’. There are countless cases where we want to find common elements between two lists in Python. In this tutorial, we’ll explain the different options we have at our disposal to achieve this objective.

Use set() to find common elements between two lists in Python

You can use the set() data type to find quickly the common elements. One of the main characteristics of a set() is that it can’t contain duplicates values; hence, the common elements returned will be unique.

#our lists list1 = ['apple','banana','strawberry'] list2 = ['orange','banana','apple'] #print common values print(set(list1) & set(list2))
Code language: Python (python)

Output:

{'apple', 'banana'}
Code language: Python (python)

This technique is easy and straightforward, and I’d advise using it when you can. There is a similar approach using the intersection() method.

#our lists list1 = ['apple','banana','strawberry'] list2 = ['orange','banana','apple'] #print common values print(set(list1).intersection(list2))
Code language: Python (python)

Output:

{'apple', 'banana'}
Code language: Python (python)

If you’re not familiar with this method, the code behind it is available below. It leverages two for loops to get the job done:

def intersect(a, b): if len(a) > len(b): a, b = b, a c = set() for x in a: if x in b: c.add(x) return c
Code language: Python (python)

Use a list comprehension to find common elements in two lists

If you don’t want to use the built-in intersection method, you can build your own list comprehension to achieve the same result.

#our lists list1 = ['apple','banana','strawberry'] list2 = ['orange','banana','apple'] #print common values print([element for element in list1 if element in list2])
Code language: Python (python)

The main differences between the first technique and this one:

  • Result is a list, not a set
  • Code is less readable because you don’t use a method known by most Python users

Leave a Reply

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