Check if two Python sets have at least one common element

Viewed 1850

What is the fastest way to check if two sets in Python have at least one common element? The desired output is a True/False.

e.g. I tried with set.intersection(), but I would like to avoid checking all the elements in both sets.

set.intersection({1,2,3}, {8,9,2})
>>> {2}

NOTE: I'm searching for a very efficient solution that works with Python sets (I'm not asking about lists)

2 Answers

{1,2,3}.isdisjoint({4,5,6}) will return true since there is no intersection.

def intersect(a, b):
    if len(a) > len(b):
        a, b = b, a   
    for c in a:
        if c in b:
            return c

The above code is similar to the implementation of intersection( ), except that this version returns the first element that is matched. You could also return true if required, instead of the first matched element.

Related