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 Programming skills with w3resource's quiz.



Python: Tips of the Day

Use Reversed() In for Loops:

>>> tasks = ['laundry', 'picking up kids', 'gardening', 'cooking']
>>> for task in reversed(tasks):
...     print(task)
... 
cooking
gardening
picking up kids
laundry