Biginor
Biginor

Reputation: 13

How to subtract two list in python

Friends, I need help to subtract two list as below, appreciate kind support on this.

ListA=['a','b','b','b','c','c','d','e','f','f','g','h']
ListB=['a','b','c','d','e','f','f','g']

Answer i need as listC

Listc=['b','b','c','h']

I tried this with set, but not getting answer as i expected.Tried example as below

listC=[set(listA) - set(listB)]

Answer of the above example will be

['h']

Appreciate if someone could help me on this.

Upvotes: 1

Views: 549

Answers (1)

McGrady
McGrady

Reputation: 11477

You can use this list comprehension to iterate the list, if the item in ListB remove it:

>>> ListA=['a','b','b','b','c','c','d','e','f','f','g','h']
>>> ListB=['a','b','c','d','e','f','f','g']
>>>
>>> [i for i in ListA if i not in ListB or ListB.remove(i)]
['b', 'b', 'c', 'h']

Using a list comprehension doesn't build a list, because of the overhead of creating and extending list, list comprehensions is faster than old loop, the above list comprehension is equivalent to this:

r=[]
for i in ListA:
    if i in ListB:
        ListB.remove(i)
    else:
        r.append(i)
print(r)

Upvotes: 1

Related Questions