8.1 Operators and Methods Table
Python supports operator overloading, which means you can operate on objects not only using methods but also using operators like: +
, -
, *
, /
, |
, and so on.
The set
class has overloaded all possible operators to make working with sets easy and very similar to how it's done in math.
Here's the table of such operators:
Operator | Method | Description |
---|---|---|
| |
union() |
Returns the union of two sets. |
& |
intersection() |
Returns the intersection of sets (only common elements). |
- |
difference() |
Returns the difference of sets (elements present in the first set only). |
^ |
symmetric_difference() |
Returns the symmetric difference of sets (elements present in one of the sets, but not both). |
<= |
issubset() |
Checks if one set is a subset of another. |
< |
issubset() |
Checks if one set is a proper subset of another (strict subset). |
>= |
issuperset() |
Checks if one set is a superset of another. |
> |
issuperset() |
Checks if one set is a proper superset of another (strict superset). |
== |
__eq__() |
Checks if sets are equal (contain the same elements). |
!= |
__ne__() |
Checks if sets are not equal (contain different elements). |
It's super convenient to use operators when working with sets — you'll see it for yourself in a bit.
8.2 Working with Sets Using Operators
Union (OR)
Operator | | Using union() function |
---|---|
|
|
Intersection (AND)
Operator & | Using intersection() function |
---|---|
|
|
Difference (DIFFERENCE)
Operator - | Using difference() function |
---|---|
|
|
Symmetric Difference (SYMMETRIC DIFFERENCE)
Operator ^ | Using symmetric_difference() function |
---|---|
|
|
It's kinda weird that operators like +
or *
aren't used, but hey, Python developers have their reasons.
GO TO FULL VERSION