7.3. Sets#
Formal mathematical sets
Do not have duplicate values
Are not ordered
Cannot access via index.
Useful for doing set operations
Can have different data types
A = {0, 2, 4, 6, 8}
B = {1, 2, 3, 4, 5}
7.3.1. Check if a value belongs#
2 in A
True
7.3.2. Union – all values#
A | B
{0, 1, 2, 3, 4, 5, 6, 8}
7.3.4. Difference – order matters#
A - B
B - A
7.3.5. Check Subset#
A = {1, 2, 3, 4, 5}
B = {3, 4}
B < A
True
A = {1, 2, 3, 4, 5}
B = {3, 4}
B <= A
True
A = {1, 2, 3, 4, 5}
B = {3, 4}
B > A
False
7.3.6. Adding a single element#
A = {1, 2, 3, 4, 5}
A.add(6)
print(A)
{1, 2, 3, 4, 5, 6}
A = {1, 2, 3, 4, 5}
A.add(1)
print(A)
{1, 2, 3, 4, 5}
7.3.7. Removing an element#
Three ways
7.3.7.1. Discard#
Will NOT raise an error if the element being remove is not in set.
A = {1, 2, 3, 4, 5}
A.discard(1)
print(A)
A.discard('P')
{2, 3, 4, 5}
7.3.7.2. Remove#
Will raise an error if the element being remove is not in set.
A = {1, 2, 3, 4, 5}
A.remove(1)
print(A)
A.remove('P')
{2, 3, 4, 5}
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
Cell In[11], line 4
2 A.remove(1)
3 print(A)
----> 4 A.remove('P')
KeyError: 'P'
7.3.7.3. Pop#
Will remove an element
A = {1, 2, 3, 4, 5}
A.pop()
1
7.3.8. Checking if multiple dictionary keys exist#
d1 = dict(a=1, b=2, c=3, d=4)
d2 = dict(b=20, d=40, e=50)
d1.keys() & d2.keys() # this works because dict.keys() returns "set-like" view rather than a list
{'b', 'd'}
{'b', 'd'}
d1 = dict(a=1, b=2, c=3, d=4)
d2 = dict(b=20, d=40, e=50)
d1.keys() <= {'a', 'b', 'c', 'd'}
True
7.3.9. Symmetric difference#
https://en.wikipedia.org/wiki/Symmetric_difference
A = {1, 2, 3, 4, 5}
B = {3, 4}
A ^ B
{1, 2, 5}