Subtract String Lists in Python
Sometimes, while working with lists, we can have a problem in which we need to remove one list elements from other, i.e perform subtraction. This has application across many domains. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using loop + remove()
The combination of above functionalities can be used to perform this task. In this, we perform the removal of elements using remove() and check for similar elements using loop.
Python3
test_list1 = [ "gfg" , "is" , "best" , "for" , "CS" ]
test_list2 = [ "preferred" , "is" , "gfg" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = [ ele for ele in test_list1 ]
for a in test_list2:
if a in test_list1:
res.remove(a)
print ( "The Subtracted list is : " + str (res))
|
Output
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #2 : Using Counter() + elements()
The combination of the above functions provides a shorthand to solve this problem. In this, we extract the count of elements in both list and then perform separation by their extraction using element().
Python3
from collections import Counter
test_list1 = [ "gfg" , "is" , "best" , "for" , "CS" ]
test_list2 = [ "preferred" , "is" , "gfg" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = list ((Counter(test_list1) - Counter(test_list2)).elements())
print ( "The Subtracted list is : " + str (res))
|
Output
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']
Time complexity: O(M^N) as the number of combinations generated is M choose N.
Auxiliary space: O(M^N) as the size of the resultant list is also M choose N.
Method #3 : Using filter() + lambda
Python3
test_list1 = [ "gfg" , "is" , "best" , "for" , "CS" ]
test_list2 = [ "preferred" , "is" , "gfg" ]
print ( "The original list 1 : " + str (test_list1))
print ( "The original list 2 : " + str (test_list2))
res = list ( filter ( lambda x: x not in set (test_list2),test_list1))
print ( "The Subtracted list is : " + str (res))
|
Output
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']
Time complexity: O(n)
Space complexity: O(n) where n is number of elements in both lists
Last Updated :
09 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...