Python | Difference between two lists, including duplicates



Method # 1: Using collections.Counter()
The Counter method can be used to get the exact occurrence of items in a list and therefore can selectively subtract rather than using a set and ignoring the number of items in general. You can then subtract to get the actual occurrence.

# Python3 demo code
# List difference, including duplicates
# Using collection.Counter ()

from collections import Counter

 
# initializing lists

test_list1 = [ 1 , 3 , 4 , 5 , 1 , 3 , 3 ]

test_list2 = [ 1 , 3 , 5 ]

 
# printing original lists

print ( "The original list 1:" + str (test_list1))

print ( " The original list 2: " + str (test_list2))

 
# Using collection.Counter ()
# Difference in the list, including duplicates

res = list ((Counter (test_list1) - Counter (test_list2)) .elements ())

 
# print result

print ( "The list after performing the subtraction:" + str (res))

Output:

 The original list 1: [1, 3, 4, 5 , 1, 3, 3] The original list 2: [1, 3, 5] The list after performing the subtraction: [1, 3, 3, 4] 

 Method # 2: Using map () + lambda + remove ()
A combination of the above functions can be used to accomplish this particular task. The map function can be used to bind a function to all elements and remove that removes its first occurrence. Therefore, it does not delete again. Only works with Python2.

# Python code for demo
# List difference including duplicates
# Using map () + lambda + remove ()

 
# initializing lists

test_list1 = [ 1 , 3 , 4 , 5 , 1 , 3 , 3 ]

test_list2 = [ 1 , 3 , 5 ]

 
# print original lists

print ( "The original list 1:" + str (test_list1))

print ( "The original list 2:" + str (test_list2))

 
# Using map () + lambda + remove ()
# List difference including duplicates

res = map ( lambda x: test_list1.remove (x) 

if x in test_list1 else None , test_list2)

 
# print result

print ( "The list after performing the subtraction:" + str (test_list1))

Output:

 The original list 1: [1, 3, 4, 5, 1 , 3, 3] The original list 2: [1, 3, 5 ] The list after performing the subtraction: [1, 3, 3, 4]