Try it here
Subscribe
Common elements in 2 lists

How to find common elements in two lists in Python ?

how_to_find_common_elements_in_two_lists_in_python_

There are many ways to find the common elements in two lists. Some of them are mentioned below :

Using list Comprehension technique with if condition:

>>> a=[i for i in range (5,10)]
>>> a
[5, 6, 7, 8, 9]
>>> b=[i for i in range(7,15)]
>>> b
[7, 8, 9, 10, 11, 12, 13, 14]
>>> common=[c for c in a if c in b]
>>> common
[7, 8, 9]
>>> 

Here both the lists a and b has common elements [7,8,9] .

Using set's & operator:

>>> c= list(set(a) & set(b))
>>> c
[8, 9, 7]
>>> 

Using set().intersection()

>>> c=list(set(a).intersection(b))
>>> c
[8, 9, 7]
>>> 

Writer profile pic

Anmol on Apr 18, 2020 at 07:04 am


This article is contributed by Anmol. If you like dEexams.com and would like to contribute, you can write your article here or mail your article to admin@deexams.com . See your article appearing on the dEexams.com main page and help others to learn.



Post Comment

Comments( 0)

WEB TECHNOLOGY

Articles

×

Forgot Password

Please enter your email address below and we will send you information to change your password.