Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two Python sets have at least one common element

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)

like image 453
Dos Avatar asked Apr 30 '26 14:04

Dos


2 Answers

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

like image 114
jithin Avatar answered May 02 '26 03:05

jithin


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.

like image 28
Deepu Avatar answered May 02 '26 02:05

Deepu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!