- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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]
Advertisements