krumpelstiltskin krumpelstiltskin - 6 months ago 31
Python Question

Python: test empty set intersection without creation of new set

I often find myself wanting to test the intersection of two sets without using the result of the intersections.

set1 = set([1,2])
set2 = set([2,3])
if(set1 & set2):
print("Non-empty intersection")
else:
print("Empty intersection")


The problem is that a new set is created to do this test which can be inefficient.

Is there a short way to do this without explicitly writing it out (as in the following)?

if(any(x in set2 for x in set1)):
print("Non-empty intersection")
else:
print("Empty intersection")

Answer

You are looking for set.isdisjoint(), as sets are disjoint if and only if they have an empty intersection.

>>> set1 = set([1,2])
>>> set2 = set([2,3])
>>> set1.isdisjoint(set2)
False