
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference of two lists including duplicates in Python
Sometimes we need to find the differences between two lists. It will also mean a mathematical subtraction in which the elements from the first list are removed if they are present in the second list. Duplicates are preserved. Below is the approach through which we can achieve this.
We can use the Counter method from the collections module which will keep track of the count of elements. A straight mathematical subtraction gives the desired result. In the final result the number of occurrences of an element between the first and the second list will decide the elements.
Example
from collections import Counter # initializing lists listA = ['Mon', 'Tue', 9, 3, 3] listB = ['Mon', 3] # printing original lists print("Given ListA : ",listA) print("Given ListB : ",listB) # Applying collections.Counter() diff_list = list((Counter(listA) - Counter(listB)).elements()) # Result print("Result of list subtraction : ",diff_list)
Output
Running the above code gives us the following result −
Given ListA : ['Mon', 'Tue', 9, 3, 3] Given ListB : ['Mon', 3] Result of list subtraction : ['Tue', 9, 3]
- Related Questions & Answers
- Python - Combine two lists by maintaining duplicates in first list
- Commons including duplicates in array elements in JavaScript
- Python program to list the difference between two lists.
- Intersection of Two Linked Lists in Python
- Dividing two lists in Python
- Program to find minimum difference between two elements from two lists in Python
- Adding two Python lists elements
- Merge Two Sorted Lists in Python
- Combining two sorted lists in Python
- Python - Maximum difference across lists
- Python program to find Intersection of two lists?
- Concatenate two lists element-wise in Python
- How to compare two lists in Python?
- Python – Cross mapping of Two dictionary value lists
- Python program to find Cartesian product of two lists
Advertisements