it-Python-courses-python-string--Python-courses-python-exercises

Exercise 18

Write a Python program that determines the symmetric difference of two lists L1 and L2, i.e. the list made up of the elements of L1 which are not in L2 and the elements of L2 which are not in L1 Example if: L1 = [11, 3, 22, 7, 13, 23, 9] L2 = [5, 9, 19, 23, 22, 23, 13]The program returns the list [11, 3, 7, 5, 19]

Solution

def symetricDifference(L1 , L2):
# initialiser la liste difference sysmétrique de L1 et L2
diffSym = []
for x in L1:
if x not in L2:
diffSym.append(x)
for x in L2:
if x not in L1:
diffSym.append(x)
return diffSym
#Example
L1 = [11 , 3 , 22 , 7 , 13 , 23 , 9]
L2 = [5 , 9 , 19 , 23 , 22 , 23 , 13]
print("The symetric difference of L1 and L2 is : " , symetricDifference(L1 , L2))
# The output is: The symetric difference of L1 and L2 is : [11, 3, 7, 5, 19]

Younes Derfoufi
my-courses.net

Leave a Reply