how to substract a list of strings from another in python

To subtract a list of strings from another, you can use list comprehension along with not in operator. Here's an example:

main.py
list1 = ['apple', 'orange', 'banana', 'kiwi']
list2 = ['banana', 'kiwi']

result_list = [item for item in list1 if item not in list2]

print(result_list) # Output: ['apple', 'orange']
184 chars
7 lines

In the code above, we first declare list1 and list2 containing the lists of strings that we want to subtract. We then use list comprehension to create a filtered list that contains only the elements from list1 that are not in list2. The result is stored in result_list.

The output indicated on the comment should be ['apple', 'orange'] which is list1 without list2 elements.

I hope this helps!

related categories

gistlibby LogSnag