Skip to content Skip to sidebar Skip to footer

How To Subtract Two Iterables In Python

There are two lists A and B. I want to get all the elements in A but not in B. Any efficient way to do this?

Solution 1:

You can use a list comprehension to do this for you.

filtered = [i for i in A if i not in B]

If the lists are both large, you might want to consider creating a set from B for faster membership lookup

setB = set(B)
filtered = [i for i in A if i not in setB]

This solution maintains the order of A and any duplicates that exist in A.

Solution 2:

i always like to use sets for this:

set(A) - set(B)

edit: except if A has duplicates or you care about order, then use @Cyber's answer

Solution 3:

sets are great for this purpose

set(A) - set(B)

eg

>>> set([2,2,2,3,3,4])- set([1,2,2,4,5])
set([3])

btw. this looks like this

Post a Comment for "How To Subtract Two Iterables In Python"