Fix Python – Returning boolean if set is empty


Asked By – C.B.

I am struggling to find a more clean way of returning a boolean value if my set is empty at the end of my function

I take the intersection of two sets, and want to return True or False based on if the resulting set is empty.

def myfunc(a,b):
    c = a.intersection(b)
    #...return boolean here

My initial thought was to do

return c is not None

However, in my interpreter I can easily see that statement will return true if c = set([])

>>> c = set([])
>>> c is not None

I’ve also tried all of the following:

>>> c == None
>>> c == False
>>> c is None

Now I’ve read from the documentation that I can only use and, or, and not with empty sets to deduce a boolean value. So far, the only thing I can come up with is returning not not c

>>> not not c
>>> not c

I have a feeling there is a much more pythonic way to do this, by I am struggling to find it. I don’t want to return the actual set to an if statement because I don’t need the values, I just want to know if they intersect.

Now we will see solution for issue: Returning boolean if set is empty


def myfunc(a,b):
    c = a.intersection(b)
    return bool(c)

bool() will do something similar to not not, but more ideomatic and clear.

This question is answered By – Jonas Schäfer

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0