The Python Oracle

Test if lists share any items in python

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

--

Track title: CC I Beethoven Sonata No 31 in A Flat M

--

Chapters
00:00 Question
00:48 Accepted answer (Score 469)
06:29 Answer 2 (Score 28)
06:50 Answer 3 (Score 11)
07:45 Answer 4 (Score 6)
07:58 Thank you

--

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

Accepted answer links:
[here]: https://wiki.python.org/moin/TimeComplex...
[here]: https://wiki.python.org/moin/TimeComplex...
[here]: https://docs.python.org/3.5/library/stdt...
[image]: https://i.stack.imgur.com/GUmOo.png
[image]: https://i.stack.imgur.com/sXnuN.png
[image]: https://i.stack.imgur.com/csO66.png
[image]: https://i.stack.imgur.com/02Q7s.png
[image]: https://i.stack.imgur.com/xPXYL.png
[image]: https://i.stack.imgur.com/qXoqC.png

--

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