Reputation: 1
I was looking for some help to write a Python script to print only the difference and not anything extra in the output.
For example:
Contents of File1 :-
['Tom','Joe','Kim']
Contents of File2 :-
['Tom','Leo','Cho','Joe','Kim']
I need the following as output when I run the script:
['Leo','Cho']
I tried using difflib library functionalities, but it just doesn't seem to give me only the difference as output!
Upvotes: -2
Views: 61
Reputation: 1313
You can use the set.union(..) and set.intersection(..) methods to obtain what you are looking for. It is included in standard, no import to make:
file1 = ['Tom','Joe','Kim']
file2 = ['Tom','Leo','Cho','Joe','Kim']
result = set(file1).union(set(file2)) - set(file1).intersection(set(file2))
print( list(redsult) )
Output is:
['Leo', 'Cho']
Upvotes: 0
Reputation: 1088
file1 = ['Tom','Joe','Kim']
file2 = ['Tom','Leo','Cho','Joe','Kim']
diff = list(set(file2)-set(file1)
Output:
['Cho', 'Leo']
Note, if don't know from which list to subtract (i.e the largest one) you can use the following code. It uses "OR" operator:
diff = list(set(file2)-set(file1)|set(file1)-set(file2))
Upvotes: 1