Python - Difference of List keeping duplicates
Last Updated :
31 Mar, 2023
The problem of finding difference between list, i.e removing elements that occur in one list and not in other is discussed before. But the usage of sets ignores duplicates and we sometimes, require to remove the exact elements that occur in lists. Lets discuss certain ways in which this task can be performed.
Method #1 : Using loop This is brute way in which this task can be performed. In this, we extract the elements in a form in which we remove elements each time and break the loop to remove one element at a time.
Python3
# Python3 code to demonstrate
# Difference of List keeping duplicates
# using loop
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Difference of List keeping duplicates
# using loop
for ele in test_list2:
for sub in test_list1:
if ele == sub:
test_list1.remove(sub)
break
# printing result
print ("List after performing difference : " + str(test_list1))
Output : The original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [5, 4]
Time Complexity: O(n*n) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.
Method #2 : Using pop() + list comprehension + index() This task can also be performed using combination of above functionalities. In this, we just iterate the list using list comprehension and remove element using index() and pop().
Python3
# Python3 code to demonstrate
# Difference of List keeping duplicates
# using pop() + list comprehension + index()
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Difference of List keeping duplicates
# using pop() + list comprehension + index()
[test_list1.pop(test_list1.index(idx)) for idx in test_list2]
# printing result
print ("List after performing difference : " + str(test_list1))
Output : The original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [5, 4]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(k), where k is the number of unique elements in the input list (determined by creating a set of the input list).
Method #3 : Using collections.Counter()
This task can also be performed using collections.Counter() which simply counts the occurrence of each element and subtracts the corresponding elements.
Python3
# Python3 code to demonstrate
# Difference of List keeping duplicates
# using collections.Counter()
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Difference of List keeping duplicates
# using collections.Counter()
from collections import Counter
res = Counter(test_list1) - Counter(test_list2)
# printing result
print ("List after performing difference : " + str(list(res.elements())))
OutputThe original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [4, 5]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using the deque() function from the collections module:
Algorithm:
- Convert test_list1 and test_list2 to deques.
- For each element x in test_list2, try to remove it from the deque d. Ignore ValueError exceptions if x is not in d.
- Convert d back to a list and store it in res.
Python3
from collections import deque
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
d = deque(test_list1)
d2 = deque(test_list2)
for x in d2:
try:
d.remove(x)
except ValueError:
pass
res = list(d)
# printing result
print ("List after performing difference : " + str(res))
#This code is contributed by Jyothi pinjala.
OutputThe original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [5, 4]
Time Complexity:
- Converting test_list1 and test_list2 to deques takes O(n) time where n is the length of test_list1.
- The for loop iterates over each element in test_list2, so its time complexity is O(m) where m is the length of test_list2.
- The remove() method on a deque has O(1) time complexity on average, but O(n) in the worst case when the element is not found, so the worst-case time complexity of the try-except block is O(mn).
- Converting the deque back to a list takes O(n) time.
- Overall, the worst-case time complexity of the algorithm is O(mn).
Auxiliary Space:
- Converting test_list1 and test_list2 to deques uses O(n) space.
- The res list uses O(n) space.
- The d and d2 deques use O(n) + O(m) = O(n+m) space.
- Overall, the space complexity of the algorithm is O(n+m).
Method #5 : Using itertools and collections:
Algorithm :
- Import the required modules, itertools and collections.
- Initialize two lists, test_list1 and test_list2 with some elements.
- Print the original lists.
- Use itertools.chain() function to concatenate the elements of both lists into a single iterator.
- Use collections.Counter() function on the iterator to get the count of each element.
- Use the '-' operator between the two Counter objects to find the difference between the two lists, keeping duplicates.
- Convert the result Counter object to a list using the elements() function.
- Print the final result.
Python3
# Python3 code to demonstrate
# Difference of List keeping duplicates
# using collections.Counter() and itertools.chain()
import itertools
from collections import Counter
# Initializing lists
test_list1 = [4, 5, 7, 4, 3]
test_list2 = [7, 3, 4]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Difference of List keeping duplicates
# using collections.Counter() and itertools.chain()
res = Counter(itertools.chain(test_list1)) - Counter(itertools.chain(test_list2))
# printing result
print ("List after performing difference : " + str(list(res.elements())))
#This code is contributed by Rayudu.
OutputThe original list 1 is : [4, 5, 7, 4, 3]
The original list 2 is : [7, 3, 4]
List after performing difference : [4, 5]
Time complexity: O(n), where n is the length of the concatenated list of elements. This is because we need to iterate over all the elements of the concatenated list to count their occurrences.
Auxiliary Space: O(n), where n is the length of the concatenated list of elements. This is because we need to create two Counter objects, each of which would store the count of each element in the concatenated list.
Similar Reads
Python - Difference of Two Lists Including Duplicates
We are given two list we need find difference between two list. For example, a = [1, 2, 2, 3, 4] and b = [2, 3] we need to find difference of two list so that resultant output should be [1, 2, 4].Using a for loopA for loop can iterate through first list and remove matching elements from second list
2 min read
List Product Excluding Duplicates - Python
The task of finding the product of unique elements in a list involves identifying and multiplying only the distinct values, effectively excluding any duplicates. For example, if a = [1, 3, 5, 6, 3, 5, 6, 1], the unique elements would be {1, 3, 5, 6}, and the product of these values would be 90. Usin
3 min read
Python - K difference index pairing in list
Sometimes while programming, we can face a problem in which we need to perform K difference element concatenation. This problem can occur at times of school programming or competitive programming. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using list comprehension +
5 min read
Python | Difference in Record Lists
Sometimes, while working with data, we may have a problem in which we require to find the difference records between two lists that we receive. This is a very common problem and records usually occurs as a tuple. Letâs discuss certain ways in which this problem can be solved. Method #1 : Using list
5 min read
Python | Maximum absolute difference list of list
This particular article focuses on a problem that has utility in competitive as well as day-day programming. Sometimes, we need to get the maximum difference between the like indices when compared with the next list. The maximum difference between the like elements in that index is returned. Let's d
7 min read
Python - Merging duplicates to list of list
We are given a list we need to merge the duplicate to lists of list. For example a list a=[1,2,2,3,4,4,4,5] we need to merge all the duplicates in lists so that the output should be [[2,2],[4,4,4]]. This can be done by using multiple functions like defaultdict from collections and Counter and variou
3 min read
Removing Duplicates of a List of Sets in Python
Dealing with sets in Python allows for efficient handling of unique elements, but when working with a list of sets, you may encounter scenarios where duplicates need to be removed. In this article, we will see how we can remove duplicates of a list of sets in Python. Remove Duplicates of a List of S
2 min read
Python | Set Difference in list of dictionaries
The difference of two lists have been discussed many times, but sometimes we have a large number of data and we need to find the difference i.e the elements in dict2 not in 1 to reduce the redundancies. Let's discuss certain ways in which this can be done. Method #1 : Using list comprehension The na
3 min read
Python - Remove Duplicates from a list And Keep The Order
While lists provide a convenient way to manage collections of data, duplicates within a list can sometimes pose challenges. In this article, we will explore different methods to remove duplicates from a Python list while preserving the original order.Using dict.fromkeys()dict.fromkeys() method creat
2 min read
How to Find Duplicates in a List - Python
Finding duplicates in a list is a common task in programming. In Python, there are several ways to do this. Letâs explore the efficient methods to find duplicates. Using a Set (Most Efficient for Large Lists)Set() method is used to set a track seen elements and helps to identify duplicates. Pythona
2 min read