Set Operations using Methods and Builtins
suggest changeWe define two sets a
and b
>>> a = {1, 2, 2, 3, 4}
>>> b = {3, 3, 4, 4, 5}
NOTE: {1} creates a set of one element, but {} creates an empty dict. The correct way to create an empty set is set().
Intersection
a.intersection(b)
returns a new set with elements present in both a
and b
>>> a.intersection(b)
{3, 4}
Union
a.union(b)
returns a new set with elements present in either a
and b
>>> a.union(b)
{1, 2, 3, 4, 5}
Difference
a.difference(b)
returns a new set with elements present in a
but not in b
>>> a.difference(b)
{1, 2}
>>> b.difference(a)
{5}
Symmetric Difference
a.symmetric_difference(b)
returns a new set with elements present in either a
or b
but not in both
>>> a.symmetric_difference(b)
{1, 2, 5}
>>> b.symmetric_difference(a)
{1, 2, 5}
NOTE: a.symmetric_difference(b) == b.symmetric_difference(a)
Subset and superset
c.issubset(a)
tests whether each element of c
is in a
.
a.issuperset(c)
tests whether each element of c
is in a
.
>>> c = {1, 2}
>>> c.issubset(a)
True
>>> a.issuperset(c)
True
The latter operations have equivalent operators as shown below:
|Method |Operator |
|––––––––––––––|––––––––|
|`a.intersection(b)` | `a & b` |
|`a.union(b)` | `a`|`b` |
|`a.difference(b)` | `a - b` |
|`a.symmetric_difference(b)` | `a ^ b` |
|`a.issubset(b)` | `a <= b` |
|`a.issuperset(b)` | `a >= b` |
Disjoint sets
Sets a
and d
are disjoint if no element in a
is also in d
and vice versa.
>>> d = {5, 6}
>>> a.isdisjoint(b) # {2, 3, 4} are in both sets
False
>>> a.isdisjoint(d)
True
# This is an equivalent check, but less efficient
>>> len(a & d) == 0
True
# This is even less efficient
>>> a & d == set()
True
Testing membership
The builtin in
keyword searches for occurances
>>> 1 in a
True
>>> 6 in a
False
Length
The builtin len()
function returns the number of elements in the set
>>> len(a)
4
>>> len(b)
3