Exercise17
Write a Python program that determines the difference of two lists. Example if: L1 = [11, 3, 22, 7, 13, 23, 9] L2 = [5, 9, 19, 23, 10, 23, 13]the program returns the list: [11, 3, 22, 7]
Solution
def differenceList (L1, L2):
# initialize the difference list of L1 and L2
diff = []
for x in L1:
if x not in L2:
diff.append (x)
return diff
#Example
L1 = [11, 3, 22, 7, 13, 23, 9]
L2 = [5, 9, 19, 23, 10, 23, 13]
print ("The difference of L1 and L2 is:", differenceList (L1, L2))
# The output is: The difference of L1 and L2 is: [11, 3, 22, 7]
Younes Derfoufi
my-courses.net
my-courses.net