How to find common elements (e.g. intersection) between two lists in python ?

September 21, 2021    /    Viewed: 190    /    Comments: 0    /    Edit


Examples of how to find common elements between two lists in python:

Create two lists in python

Let's create a list in python

list_a = ['e','0', 6, 'f', 4, 1, 'g']

and another

list_b = ['a','d', 1, 'o', 8, 3, 'e']

Find common elements between two lists

To find common elements between two lists, a solution is to use Python Set intersection() Method. To do so, let's first convert one of the two lists in a set:

list_a_as_set = set(list_a)

and then apply intersection

intersection = list_a_as_set.intersection(list_b)

for i in intersection:
    print( i )

returns here

1
e

Note that:

type(intersection)

is a set.

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!