Creating sets
A set can be created using curly braces or the explicit
set(iterable)
:
Note:
{}
does not create an empty set, rather, it creates an empty
dict.
S1 = set([ 1, 7, 3])
S2 ={ 'one', 'seven', 'three' }
S3 ={}
print(type(S1))
#
# <class 'set'>
print(type(S2))
#
# <class 'set'>
print(type(S3))
#
# <class 'dict'>
Because a
string (str
) is also an iterable, a set can be created from a string. The elements in such a set consists of characters:
S = set('hello world')
print(S)
#
# {'h', 'd', 'o', 'r', 'w', ' ', 'e', 'l'}
Set operators
The set
type has four operators that return sets:
Mathematical operator | Alias | |
S1 - S2 | S1.difference(S2) | All elements of S1 that are not in S2 |
S1 & S1 | S1.intersection(S2) | All elements of S1 that are also in S2 |
S1 | S1 | S1.union(S2) | All elements of S1 and S1 |
S1 ^ S1 | S1.symmetric_difference(S2) | All elements of S1 that are not in S2 plus all elements of S2 that are not in S1 . |
even = { 2, 4, 6, 8, 10, 12 }
odd = { 1, 3, 5, 7, 9, 11 }
prime = { 2, 3, 5, 7, 11 }
print(prime - odd)
#
# {2}
print(prime & even)
#
# {2}
print(even | prime)
#
# {2, 3, 4, 5, 6, 7, 8, 10, 11, 12}
print(odd ^ prime)
#
# {1, 2, 9}
Testing membership in a set
prime = {2, 3, 5, 7, 11, 13}
if 4 in prime:
print('4 is a prime')
else:
print('4 is not a prime')
if 6 not in prime:
print('6 is not a prime')
else:
print('6 is a prime')
Additionally, S1 <= S2
and S1 >= S2
can be used to test whether a S1
is a subset or superset, respectively, of S2
. In this context, these operators can also be called with the explicit names S1.issubset(S2)
and S1.issuperset(S2)
.
Find unique values in a list
A set can be used to find unique values in a
list:
a = ['foo', 'baz', 'baz', 'bar', 'foo', 'bar', 'baz', 'foo', 'bar']
s = set(a)
print(' - '.join(list(s)))
#
# foo - baz - bar