HighAllegiant
HighAllegiant

Reputation: 71

Python Filtering 2 Lists

I'm trying to find a way to use one list to filter out elements of another.

Kinda like the intersect syntax but the exact opposite

lst = [0,1,2,6]

secondlst = [0,1,2,3,4,5,6]

expected outcome

[3,4,5]

Upvotes: 2

Views: 7630

Answers (4)

Jeff
Jeff

Reputation: 7210

You can use filter

filter(lambda x: x not in lst, secondlst)

Upvotes: 3

rob mayoff
rob mayoff

Reputation: 385500

Simple:

outcome = [x for x in secondlst if x not in lst]

More complex but faster if lst is large:

lstSet = set(lst)
outcome = [x for x in secondlst if x not in lstSet]

Upvotes: 1

jathanism
jathanism

Reputation: 33716

Look no further than Python's set()' type.

>>> lst = [0,1,2,6]
>>> secondlst = [0,1,2,3,4,5,6]
>>> set(lst).symmetric_difference(set(secondlst))
set([3, 4, 5])

Upvotes: 2

koblas
koblas

Reputation: 27048

Simple way:

r = [v for v in secondlst if v not in lst]

or

list(set(secondlst).difference(lst))

Upvotes: 12

Related Questions