Python exercise : Find common elements between two lists




Python exercise


Episode: 4 

Level: Beginner 

In this episode we will write function in Python 3 which finds and prints common elements between two lists.

Let's say we have two lists:

A = [2, 73, "Flanture", 5, "blog"]

B = ["Blog", 2, 44, "Flanture", 72]

Write function intersection with two arguments and return list with common elements as a result.

Solution:
 
def intersection(a, b):  
   common = []  

   for el in a:  
     if el in b:  
       common.append(el)  
   return common  


A = [2, 73, "Flanture", 5, "blog"]  
B = ["Blog", 2, 44, "Flanture", 72]  

result = intersection(A, B)  

print(result)  

# output : [2, 'Flanture']  


Shorter version uses list comprehensions:

 
def intersection(a, b):  
   return [el for el in a if el in b]  

A = [2, 73, "Flanture", 5, "blog"]  
B = ["Blog", 2, 44, "Flanture", 72]  

print(intersection(A, B))  

# output : [2, 'Flanture']  


Which version do you prefer?

P.S. Why string "blog" is not common element of lists A and B?


Post a Comment

0 Comments