Search notes:

Python: set

A set contains unique and unordered objects.

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'>
Github repository about-python, path: /types/set/create.py
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'}
Github repository about-python, path: /types/set/create-from-string.py

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}
Github repository about-python, path: /types/set/set-operators.py

Testing membership in a set

The in and not in operators can be used to test for 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')
Github repository about-python, path: /types/set/in.py
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
Github repository about-python, path: /types/set/find-unique-values-in-list.py

See also

Compare with frozenset
The collections module.
Other Built-in types

Index