The Python Oracle

How to check if an element from List A is not present in List B in Python?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Realization

--

Chapters
00:00 How To Check If An Element From List A Is Not Present In List B In Python?
00:26 Answer 1 Score 9
00:51 Answer 2 Score 7
01:04 Accepted Answer Score 4
01:23 Answer 4 Score 2
01:31 Answer 5 Score 1
01:44 Thank you

--

Full question
https://stackoverflow.com/questions/3089...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list

#avk47



ANSWER 1

Score 10


if the items in the list are hashable:

>>> set(A) - set(B)
{1, 2, 3}

otherwise, you may use filter function:

>>> list(filter(lambda a: a not in B, A))
[1, 2, 3]

in that case, if B is sorted, you may get a better performance by using bisect.bisect_left to search logarithmically:

>>> def pred(a):  # if B is already *sorted*
...     from bisect import bisect_left
...     i = bisect_left(B, a)
...     return i == len(B) or B[i] != a
... 
>>> list(filter(pred, A))
[1, 2, 3]



ANSWER 2

Score 7


You can also use list comprehension:

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

Output:

[1, 2, 3]



ACCEPTED ANSWER

Score 4


Using list comprehension:

truthy answer

any([True for x in [1, 2, 3, 4] if x in [4, 5, 6, 7]])

list of elements not present in the second list

[x for x in [1, 2, 3, 4] if x not in [4, 5, 6, 7]]



ANSWER 4

Score 1


That's a typical case for boolean operations on sets:

zerotonine = set(range(10))
fourtoten = set(range(4,11))
print "exclusively in one:", zerotonine ^ fourtoten
exclusively in one: set([0, 1, 2, 3, 10])