The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

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

--

Chapters
00:00 Question
00:32 Accepted answer (Score 2)
00:52 Answer 2 (Score 6)
01:29 Answer 3 (Score 4)
01:44 Answer 4 (Score 2)
01:55 Thank you

--

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

Answer 1 links:
[filter]: https://docs.python.org/3/library/functi...
[bisect.bisect_left]: https://docs.python.org/3.5/library/bise...

--

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])