Mathew K Analytics

Lesson 9 · Python data types deep dive

Python Sets Explained: Union, Intersection & Difference | Data Types #9

Video nine of the twelve-part series: set, Python's mutable collection of unique, unordered elements. Construction, all seventeen public set methods, the…

⬇ Download notebookOpen in Colab ↗

📓 Full notebook

Download .ipynb

Python Data Types Deep-Dive, Video 9: Sets (set)#

  • Video nine of the twelve-part series: set, Python's mutable collection of unique, unordered elements.
  • Construction, all seventeen public set methods, the equivalent operators, and set comprehensions.
  • Let's get into it.

Part 1: What Makes set Different#

numbers = {1, 2, 3, 2, 1}
print(numbers)
print(type(numbers))
print(len(numbers))
try:
    numbers[0]
except TypeError as e:
    print(f'Caught: {e}')
{1, 2, 3}
<class 'set'>
3
Caught: 'set' object is not subscriptable

Part 2: Set Literals and Construction#

looks_empty = {}
print(type(looks_empty))
genuine_empty_set = set()
print(type(genuine_empty_set))
from_list = set([1, 2, 2, 3])
from_string = set('mississippi')
from_tuple = set((1, 2, 3))
print(from_list, from_string, from_tuple)
<class 'dict'>
<class 'set'>
{1, 2, 3} {'m', 's', 'p', 'i'} {1, 2, 3}

Part 3: Adding Elements: add() and update()#

colors = {'red', 'green'}
colors.add('blue')
print(colors)
colors.add('red')
print(colors)
colors.update(['yellow', 'purple'])
print(colors)
colors.update({'orange'}, ['pink', 'gray'])
print(colors)
{'red', 'green', 'blue'}
{'red', 'green', 'blue'}
{'red', 'green', 'blue', 'purple', 'yellow'}
{'red', 'orange', 'green', 'blue', 'gray', 'purple', 'pink', 'yellow'}

Part 4: Removing Elements: remove(), discard(), pop(), clear()#

colors = {'red', 'green', 'blue'}
colors.remove('green')
print(colors)
try:
    colors.remove('purple')
except KeyError as e:
    print(f'Caught: {e}')
colors.discard('purple')
print(colors)
colors.discard('red')
print(colors)
{'red', 'blue'}
Caught: 'purple'
{'red', 'blue'}
{'blue'}
numbers = {5, 1, 4, 2, 3}
removed = numbers.pop()
print(removed, numbers)
numbers.clear()
print(numbers)
1 {2, 3, 4, 5}
set()

Part 5: Membership and Comparison: isdisjoint(), issubset(), issuperset()#

a = {1, 2, 3}
b = {4, 5, 6}
c = {2, 3}
print(a.isdisjoint(b))
print(a.isdisjoint(c))
print(c.issubset(a))
print(a.issubset(c))
print(a.issuperset(c))
print(c.issuperset(a))
print(c <= a)
print(a >= c)
True
False
True
False
True
False
True
True

Part 6: Combining Sets: union(), intersection(), difference(), symmetric_difference()#

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a.union(b))
print(a | b)
print(a.intersection(b))
print(a & b)
print(a.difference(b))
print(a - b)
print(b.difference(a))
print(a.symmetric_difference(b))
print(a ^ b)
{1, 2, 3, 4, 5, 6}
{1, 2, 3, 4, 5, 6}
{3, 4}
{3, 4}
{1, 2}
{1, 2}
{5, 6}
{1, 2, 5, 6}
{1, 2, 5, 6}
a = {1, 2, 3}
b = {2, 3, 4}
c = {3, 4, 5}
print(a.union(b, c))
print(a.intersection(b, c))
{1, 2, 3, 4, 5}
{3}

Part 7: In-Place Variants: intersection_update(), difference_update(), symmetric_difference_update()#

a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a.intersection_update(b)
print(a)
a = {1, 2, 3, 4}
a.difference_update(b)
print(a)
a = {1, 2, 3, 4}
a.symmetric_difference_update(b)
print(a)
{3, 4}
{1, 2}
{1, 2, 5, 6}

Part 8: copy()#

original = {1, 2, 3}
alias = original
alias.add(4)
print(original)
print(original is alias)
real_copy = original.copy()
real_copy.add(5)
print(original)
print(real_copy)
print(original is real_copy)
{1, 2, 3, 4}
True
{1, 2, 3, 4}
{1, 2, 3, 4, 5}
False

Part 9: Set Comprehensions#

squares = {n ** 2 for n in range(-3, 4)}
print(squares)
words = ['apple', 'Apple', 'BANANA', 'banana']
unique_lower = {w.lower() for w in words}
print(unique_lower)
letters = {c for c in 'mississippi' if c not in 'aeiou'}
print(letters)
{0, 9, 4, 1}
{'banana', 'apple'}
{'m', 's', 'p'}

Part 10: Practical Patterns#

raw_emails = ['a@x.com', 'b@x.com', 'a@x.com', 'c@x.com', 'b@x.com']
unique_emails = list(set(raw_emails))
print(sorted(unique_emails))
print(len(raw_emails), len(unique_emails))
['a@x.com', 'b@x.com', 'c@x.com']
5 3
import timeit
big_list = list(range(100000))
big_set = set(range(100000))
list_time = timeit.timeit(lambda: 99999 in big_list, number=1000)
set_time = timeit.timeit(lambda: 99999 in big_set, number=1000)
print(f'List membership check: {list_time:.4f}s')
print(f'Set membership check: {set_time:.4f}s')
print(f'Set is roughly {list_time / set_time:.0f}x faster here')
List membership check: 0.4743s
Set membership check: 0.0000s
Set is roughly 11186x faster here

Wrap-Up: What You Learned#

  • set holds unique, unordered, hashable elements, and is mutable.
  • Construction: literals, the set() constructor (and the empty-braces-means-dict trap).
  • Adding and removing: add, update, remove, discard, pop, clear.
  • Comparisons: isdisjoint, issubset, issuperset, and their operator shorthand.
  • Combining sets: union, intersection, difference, symmetric_difference, and their operators.
  • In-place variants: intersection_update, difference_update, symmetric_difference_update.
  • copy(), set comprehensions, and two genuinely practical real-world use cases.
  • That's all seventeen public set methods covered. Next up: frozenset, set's immutable, hashable cousin.

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.