Join us and get access to thousands of tutorials and a community of expert Pythonistas.

# Disjoint, Subset, and Superset

Copied!
Happy Pythoning!

jwiede

Might want to mention how empty set (set()) is a subset of all sets, and a proper subset of all sets (except itself, obviously).

jwiede

(sorry, hit button too soon)

This can lead to unexpected results when a set you believe contains elements is actually empty, esp. if your code expects the set in question to NOT be a subset/proper subset of another set.

Assert the set in question is a proper superset of set() in order to catch such cases. If the set in question winds up empty, that assertion will fail.

Levi

Really good point jwiede, thanks for the info.

torrepreciado

In the below example, why is it returning `False` if it’s supposed to return `True` if `c` is a superset to all the sets to the right?

``````a = {1}
b = {1, 2}
c = {1, 2, 3}

print(c >= a >= b)
``````

Bartosz Zaczyński RP Team

@torrepreciado This is a chained comparison, which would be equivalent to the following more explicit expression based on the logical AND operator:

``````>>> a = {1}
>>> b = {1, 2}
>>> c = {1, 2, 3}

>>> c >= a >= b
False

>>> c >= a and a >= b
False
``````

When you check the individual subexpressions, then you’ll find out that one of them evaluates to false, hence their logical conjunction also ends up false:

``````>>> c >= a
True
>>> a >= b
False
``````

to join the conversation.