How to get the common elements of two lists in Python

2 Answers

0 votes
def print_common_elements(lst1, lst2): 
    set1 = set(lst1) 
    set2 = set(lst2)
  
    if (set1 & set2): 
        for n in set1 & set2:
            print(n)
    else: 
        print("No common elements")  
           
   
lst1 = [1, 2, 3, 4, 5, 25, 6, 8] 
lst2 = [7, 8, 8, 9, 0, 87, 19, 2] 
 
print_common_elements(lst1, lst2)
 
 
 
'''
run:
 
8
2
 
'''

 



answered Jan 23, 2020 by avibootz
0 votes
lst1 = [1, 2, 3, 4, 5]
lst2 = [4, 7, 5, 8, 9]

print(set(lst1) & set(lst2))

    
    

'''
run:

{4, 5}

'''

 



answered Apr 17, 2021 by avibootz

Related questions

5 answers 436 views
2 answers 126 views
4 answers 308 views
1 answer 140 views
...