Open In App

Python - Difference of Two Lists Including Duplicates

Last Updated : 14 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given two list we need find difference between two list. For example, a = [1, 2, 2, 3, 4] and b = [2, 3] we need to find difference of two list so that resultant output should be [1, 2, 4].

Using a for loop

A for loop can iterate through first list and remove matching elements from second list one by one preserving duplicates. This ensures that only unmatched or extra elements remain in the result.

Python
a = [1, 2, 2, 3, 4]
b = [2, 3]
res = a.copy()

for element in b:
    # Remove the first occurrence of each element in list2 from list1
    if element in res:
        res.remove(element)

print(res)

Output
[1, 2, 4]

Explanation:

  • Loop iterates through b and for each element first occurrence is removed from res using remove preserving duplicates in a.
  • Modified list res contains elements from a after removing one instance for each match found in b which is then printed

Using collections.Counter

collections.Counter counts the frequency of elements in both lists allowing easy subtraction of counts to handle duplicates resulting Counter object can then be converted back to a list representing difference including duplicates.

Python
from collections import Counter

a = [1, 2, 2, 3, 4]
b = [2, 3]

# Count occurrences of elements in both lists
c = Counter(a)
d = Counter(b)

# Subtract counts to get the difference, including duplicates
res = list((c - d).elements())

print(res)

Output
[1, 2, 4]

Explanation:

  • Counter(a) and Counter(b) count element frequencies, and c - d subtracts counts to retain only the remaining occurrences.
  • Elements() expands resulting counts back into a list preserving duplicates and res is printed with difference

Using list comprehension

List comprehension iterates through a and checks if each element is in a copy of b. Matched elements are removed from the copy to handle duplicates accurately

Python
a = [1, 2, 2, 3, 4]
b = [2, 3]


c = b.copy()
res = []

for element in a:
    # If the element is in `c`, remove it to handle duplicates
    if element in c:
        c.remove(element)
    else:
        # If not in `c`, add the element to the result
        res.append(element)

print(res)

Output
[1, 2, 4]

Explanation:

  • List comprehension can be used to filter out elements from a that exist in b, while ensuring duplicates are correctly handled.
  • By maintaining a copy of b elements are removed as they are matched ensuring each occurrence is processed accurately.

Next Article
Practice Tags :

Similar Reads