Operators for Sets
Sets and frozen sets support the following operators:
Operators | Notes |
---|---|
key in s | containment check |
key not in s | non-containment check |
s1 == s2 | s1 is equivalent to s2 |
s1 != s2 | s1 is not equivalent to s2 |
s1 <= s2 | s1 is subset of s2 |
s1 < s2 | s1 is proper subset of s2 |
s1 >= s2 | s1 is superset of s2 |
s1 > s2 | s1 is proper superset of s2 |
s1 | s2 | the union of s1 and s2 |
s1 & s2 | the intersection of s1 and s2 |
s1 – s2 | the set of elements in s1 but not s2 |
s1 ˆ s2 | the set of elements in precisely one of s1 or s2 |
Sets in Python
A Set in Python programming is an unordered collection data type that is iterable, mutable and has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized method for checking whether a specific element is contained in the set. This is based on a data structure known as a hash table. Since sets are unordered, we cannot access items using indexes as we do in lists.