Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Subtract String Lists in Python

  • Last Updated : 04 Oct, 2021

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




# Python3 code to demonstrate working of
# Subtract String Lists
# using loop + remove()
 
# initialize lists
test_list1 = ["gfg", "is", "best", "for", "CS"]
test_list2 = ["preferred", "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))
Output
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']

 
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




# 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 = ["preferred", "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))
Output
The original list 1 : ['gfg', 'is', 'best', 'for', 'CS']
The original list 2 : ['preferred', 'is', 'gfg']
The Subtracted list is : ['best', 'for', 'CS']


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!