Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list difference

Tags:

python

list

I am trying to find all the elements 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's not.

If there a better way to achieve what I'm trying to do other than this?

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

Also important, it needs to be done in Python 2.6

like image 995
Pat Needham Avatar asked Feb 17 '12 21:02

Pat Needham


3 Answers

You're looking for the set difference:

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

Alternatively, use the minus operator:

list(set(a) - set(b))
like image 109
phihag Avatar answered Sep 26 '22 16:09

phihag


Did you try

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

Here is a list of all Python set operations.

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

like image 45
Praveen Gollakota Avatar answered Sep 26 '22 16:09

Praveen Gollakota


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]
like image 36
FogleBird Avatar answered Sep 25 '22 16:09

FogleBird