Given the list a and b, where a has one extra element compared to b, I'm trying to locate that extra element that exclusively exists in a in an efficient way. While this could be easily done using set(a) ^ set(b), the problem is that a and b could contain multiple elements with a same name that should be treated independently.
For example:
a = ['Orange', 'Orange', 'Apple', 'Tomato', 'Orange', 'Watermelon']
b = ['Watermelon', 'Orange', 'Tomato', 'Orange', 'Apple']
The result should return the extra 'Orange' that is in list a. My code is:
def ListDiff(a, b):
for element in a:
if element in b:
b.remove(element)
else:
solution = element
return solution
But obviously using the remove() can never be the most efficient and optimized way, especially if a and b are large. Is there an efficient way to locate the extra element?