Exercise 15
Write a Python program in the form of a Python function which takes two lists as parameters and returns the list of elements common to these two lists.
Solution
def listCommonElements (L1, L2):
# initialization of the list of common elements
listCommon = []
# iterate over the elements of L1 and L2 and find the common elements
for x in L1:
if x in L2:
listCommon.append (x)
return listCommon
# Example
L1 = [5, 19, 21, 7, 13, 21]
L2 = [3, 22, 19, 12, 13, 7]
print (listCommonElements (L1, L2)) # The output is: [19, 7, 13]
Younes Derfoufi
my-courses.net
my-courses.net