Sets (sets)
A set()
is a collection of unchangeable and unique elements - just as in the mathematical sense. In a sense, it is a list that does not allow duplicates. It can be created from an iterable container, e.g. a list or a tuple. Entries in a set must in turn be immutable.
set([1, 1, 0]) # Returns {0, 1}
A non-empty set can also be created directly with curly brackets {...}
. An empty set cannot be created in this way because this syntax is already reserved for the dictionary. Here, set()
must be used.
{1, 2, 3}
There are a number of operations for sets:
Operation | Description | Example | Result |
---|---|---|---|
len(s) |
Number of elements | len({1, 2, 3}) |
3 |
x in s |
Checks whether x is contained in s |
2 in {1, 2, 3} |
True |
x not in s |
Checks whether x is not contained in s |
2 not in {1, 2, 3} |
False |
s | t |
Union of s and t |
{1, 2} | {2, 3} |
{1, 2, 3} |
s & t |
Intersection of s and t |
{1, 2} & {2, 3} |
{2} |
s - t |
Difference set of s and t |
{1, 2} - {2, 3} |
{1} |
s ^ t |
Symmetric difference set of s and t |
{1, 2} ^ {2, 3} |
{1, 3} |
s <= t |
Checks whether s is a subset of t |
{1, 2} <= {1, 2, 3} |
True |
s >= t |
Checks whether s is a superset of t |
{1, 2, 3} >= {1, 2} |
True |
If you find the operator notation confusing, you can also use the method notation:
Operation | Description | Example | Result |
---|---|---|---|
s.issubset(t) |
Checks whether s is a subset of t |
{1, 2}.issubset({1, 2, 3}) |
True |
s.issuperset(t) |
Checks whether s is a superset of t |
{1, 2, 3}.issuperset({1, 2}) |
True |
s.union(t) |
Union of s and t |
{1, 2}.union({2, 3}) |
{1, 2, 3} |
s.intersection(t) |
Intersection of s and t |
{1, 2}.intersection({2, 3}) |
{2} |
s.difference(t) |
Difference set of s and t |
{1, 2}.difference({2, 3}) |
{1} |
s.symmetric_difference(t) |
Symmetric difference set of s and t |
{1, 2}.symmetric_difference({2, 3}) |
{1, 3} |