-1

I have two String Lists , i want to subtract them and strore result in a new list List_A =['A', 'B' , 'C' , 'D'] List_B =['A', 'D']

Result ['B' , 'C']

Subtracting two string lists

Najeeb
  • 1
  • 2

1 Answers1

-1

If the order of the arrays aren't important, you could implement them as sets instead and use the intersection() function.

x = {"A", "B", "C", "D"}
y = {"B", "C"}
z = x.intersection(y)

but if you want to still have them as arrays, this function will work.

def intersection(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2]
    return lst3
Lovecraft
  • 1
  • 1
  • 2
    The second version is probably the more valuable from a learning/teaching standpoint. However, for larger data, one should convert `lst2` to a set before the repeated membership tests. – user2390182 Mar 22 '23 at 12:37
  • 1
    (and convert it to set **outside** of the list comprehension) – mozway Mar 22 '23 at 12:38