What’s the algorithm of ‘set.intersection()’ in python?

The algorithm is as follows: the smaller set is looped over and every element is copied depending whether it’s found in the bigger set. So, it’s the C equivalent of

def intersect(a, b):
    if len(a) > len(b):
        a, b = b, a

    c = set()
    for x in a:
        if x in b:
            c.add(x)
    return c

(Or: return set(x for x in a if x in b).)

Leave a Comment