Difference of two lists including duplicates in Python

PythonServer Side ProgrammingProgramming

Sometimes we need to find the differences between two lists. It will also mean a mathematical subtraction in which the elements from the first list are removed if they are present in the second list. Duplicates are preserved. Below is the approach through which we can achieve this.

We can use the Counter method from the collections module which will keep track of the count of elements. A straight mathematical subtraction gives the desired result. In the final result the number of occurrences of an element between the first and the second list will decide the elements.

Example

 Live Demo

from collections import Counter

# initializing lists
listA = ['Mon', 'Tue', 9, 3, 3]
listB = ['Mon', 3]

# printing original lists
print("Given ListA : ",listA)
print("Given ListB : ",listB)

# Applying collections.Counter()
diff_list = list((Counter(listA) - Counter(listB)).elements())

# Result
print("Result of list subtraction : ",diff_list)

Output

Running the above code gives us the following result −

Given ListA : ['Mon', 'Tue', 9, 3, 3]
Given ListB : ['Mon', 3]
Result of list subtraction : ['Tue', 9, 3]
raja
Published on 04-May-2020 13:11:24
Advertisements