Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract 2 lists by duplicate elements in python

Hello I want to know how to subtract 2 lists by duplicate elements, not by value, in python.

ListA = [G, A, H, I, J, B]

ListB = [A, B, C]

ListC = [G, H, I, J] 

So we subtract the ListB values, if they are found in ListA as duplicates, and the ListC will give back the non-duplicate values in ListA.

  • Mathematically written it would be:

    ListC = ListA - (ListA ∩ ListB)

(I don't want to remove the duplicates in ListA, only the intersection between ListA and ListB, as described in the above formula, so this question is not a duplicate of questions/48242432

like image 425
Markus84612 Avatar asked Jul 02 '26 07:07

Markus84612


1 Answers

You can do a list comprehension..

[x for x in listA if x not in listB]
like image 124
Advay Umare Avatar answered Jul 03 '26 20:07

Advay Umare