w3resource

Python: Find the difference between two list including duplicate elements, use collections module

Python Collections: Exercise-26 with Solution

Write a Python program to find the difference between two list including duplicate elements. Use collections module.

Sample Solution:

Python Code:

from collections import Counter
l1 = [1,1,2,3,3,4,4,5,6,7]
l2 = [1,1,2,4,5,6]
print("Original lists:")
c1 = Counter(l1)
c2 = Counter(l2)
diff = c1-c2
print(list(diff.elements()))

Sample Output:

Original lists:
[3, 3, 4, 7]

Flowchart:

Python Collections: Find the difference between two list including duplicate elements, use collections module.

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to find the characters in a list of strings which occur more than and less than a given number.
Next: Write a Python program to remove duplicate words from a given string use collections module.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Inverts a dictionary with unique hashable values:

Example:

def tips_invert_dictionary(obj):
  return { value: key for key, value in obj.items() }
ages = {
  "Owen": 29,
  "Eddie": 15,
  "Jhon": 22,
}
print(tips_invert_dictionary(ages))

Output:

{29: 'Owen', 15: 'Eddie', 22: 'Jhon'}