Behaviour of set-intersection of objects


I stumbled upon this uncertainty in one of my programs:
Suppose we have a Class deriving from int with a custom attribute.

class A(int):
    def __new__(cls, value, *args, **kwargs):
        return super(cls, cls).__new__(cls, value)

    def __init__(self, _, a):
        self.a = a

Objects of this class are now used in a Set.

set1 = {A(2, 5), A(3, 2)}
set2 = {A(3, 7), A(5, 5)}

How would I now know the output of the following operations?

x, = set1 & set2

x, = set2 & set1

x, = set1.intersection(set2)

It appeared to me in various tests that the result is rather random, could somebody explain this behaviour?
Thank you in advance 🙂

Asked By: Raumschifffan



You intrigued me so much that I looked into source code and it became quite logical. We looped over smaller set and search every element in bigger one. When both sets has equal size, the order matters (that’s why you get different results in your case), otherwise the elements taken will always belong to smaller set.

Answered By: kosciej16
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.