Python | Print all common elements of two lists

Python Methods and Functions

Examples:

 Input: list1 = [1, 2, 3, 4, 5] list2 = [5, 6, 7, 8, 9] Output: {5} Explanation: The common elements of both the lists are 3 and 4 Input: list1 = [1, 2, 3, 4, 5] list2 = [6, 7, 8, 9] Output: No common elements Explanation: They do not have any elements in common in between them 

Method 1: Using Set & amp; property

Convert lists to sets, and then type set1 and set2 . set1 & amp; set2 returns a set of common elements, where set1 — it is list1, and set2 — this is list2.

Below is the implementation of the above approach in Python3:

# Python program for finding common elements
# in two lists

def common_member (a, b):

  a_set = set (a)

b_set = set (b)

if (a_set & amp; b_set):

  print (a_set & amp; b_set)

else :

print ( "No common elements"

 

 

a = [ 1 , 2 , 3 , 4 , 5 ]

b = [ 5 , 6 , 7 , 8 , 9 ]

common_member (a, b)

 

a = [ 1 , 2 , 3 , 4 , 5 ]

b = [ 6 , 7 , 8 , 9 ]

common_m ember (a, b)

Exit:

 {5} No common elements 

Method 1: Using the Set intersection property

Transform the list, to install by converting. Use the

# Python program for finding common elements in
# both sets using the intersect function in
# sets

 

 
# function

def common_member (a, b):

 

a_set = set (a)

b_set = set (b)

 

# check length

if len ( a_set.intersection (b_set)) & gt;  0 :

return (a_set.intersection (b_set)) 

else :

return ( "no common elements" )

 

 

a = [ 1 , 2 , 3 , 4 , 5 ]

b = [ 5 , 6 , 7 , 8 , 9 ]

print (common_member (a, b))

 

a = [ 1 , 2 , 3 , 4 , 5 ]

b = [ 6 , 7 , 8 , 9 ]

print (common_member (a, b))

Exit :

 {5} No common elements