Active September 21, 2021 / Viewed 1236 / Comments 0 / Edit

Examples of how to find common elements between 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']`

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.

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!

Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Ads

License

This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.
Ads

Ads