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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Subtract String Lists
# using loop + remove()
  
# initialize lists
test_list1 = ["gfg", "is", "best", "for", "CS"]
test_list2 = ["preffered", "is", "gfg"]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Subtract String Lists
# using loop + remove()
res = [ ele for ele in test_list1 ]
for a in test_list2:
  if a in test_list1:
    res.remove(a)
  
# printing result
print("The Subtracted list is : " + str(res))

chevron_right


Output :



The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preffered', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']

 

Method #2 : Using Counter() + elements()
The combination of above functions provide a shorthand to solve this problem. In this, we extract the count of elements in both list and then perform seperation by their extraction using element().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Subtract String Lists
# using Counter() + elements()
from collections import Counter
  
# initialize lists
test_list1 = ["gfg", "is", "best", "for", "CS"]
test_list2 = ["preffered", "is", "gfg"]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Subtract String Lists
# using Counter() + elements()
res = list((Counter(test_list1)-Counter(test_list2)).elements())
  
# printing result
print("The Subtracted list is : " + str(res))

chevron_right


Output :

The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preffered', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.