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 lists including duplicate elements. Use the collections module.
Sample Solution:
Python Code:
# Import the Counter class from the collections module
from collections import Counter
# Create two lists 'l1' and 'l2' with integer values
l1 = [1, 1, 2, 3, 3, 4, 4, 5, 6, 7]
l2 = [1, 1, 2, 4, 5, 6]
# Print a message to indicate the display of the original lists
print("Original lists:")
# Create a Counter object 'c1' to count the occurrences of elements in 'l1'
c1 = Counter(l1)
# Create a Counter object 'c2' to count the occurrences of elements in 'l2'
c2 = Counter(l2)
# Calculate the difference between 'c1' and 'c2' using '-' and store it in 'diff'
diff = c1 - c2
# Print the elements of the 'diff' Counter object as a list
print(list(diff.elements()))
Sample Output:
Original lists: [3, 3, 4, 7]
Flowchart:
Python Code Editor:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/collections/python-collections-exercise-26.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics