Python List Difference

I am trying to find all the items that are in list A and not in list B.

I thought something like newList = list(set(a) & !set(b)) or newList = list(set(a) & (not set(b))) would work, but it is not.

If there is a better way to achieve what I am trying to do other than this?

 newList = [] for item in a: if item not in b: newList.append(item) 

It is also important that this be done in Python 2.6

+4
source share
4 answers

You are looking for a given difference :

 newList = list(set(a).difference(b)) 

Alternatively, use the minus operator:

 list(set(a) - set(b)) 
+15
source

You tried

 list(set(a) - set(b)) 

The following is a list of all Python set operations .

But this unnecessarily creates a new set for b . As @phihag mentions, the difference method will prevent this.

+10
source

If you care about maintaining order:

 def list_difference(a, b): # returns new list of items in a that are not in b b = set(b) return [x for x in a if x not in b] 
+1
source
 >>> list1 = [1,2,3,4,5] >>> list2 = [4,5,6,7,8] >>> print list(set(list1)-set(list2)) [1, 2, 3] 
+1
source

Source: https://habr.com/ru/post/1397116/


All Articles