The Python Oracle

Test if lists share any items in python

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Future Grid Looping

--

Chapters
00:00 Test If Lists Share Any Items In Python
00:31 Answer 1 Score 29
00:49 Answer 2 Score 6
00:59 Answer 3 Score 11
01:41 Answer 4 Score 4
01:50 Thank you

--

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

--

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

--

Tags
#list #python #intersection

#avk47



ANSWER 1

Score 29


def lists_overlap3(a, b):
    return bool(set(a) & set(b))

Note: the above assumes that you want a boolean as the answer. If all you need is an expression to use in an if statement, just use if set(a) & set(b):




ANSWER 2

Score 11


def lists_overlap(a, b):
  sb = set(b)
  return any(el in sb for el in a)

This is asymptotically optimal (worst case O(n + m)), and might be better than the intersection approach due to any's short-circuiting.

E.g.:

lists_overlap([3,4,5], [1,2,3])

will return True as soon as it gets to 3 in sb

EDIT: Another variation (with thanks to Dave Kirby):

def lists_overlap(a, b):
  sb = set(b)
  return any(itertools.imap(sb.__contains__, a))

This relies on imap's iterator, which is implemented in C, rather than a generator comprehension. It also uses sb.__contains__ as the mapping function. I don't know how much performance difference this makes. It will still short-circuit.




ANSWER 3

Score 6


You could also use any with list comprehension:

any([item in a for item in b])



ANSWER 4

Score 4


In python 2.6 or later you can do:

return not frozenset(a).isdisjoint(frozenset(b))