Mathew K Analytics

Lesson 9 · Python data types deep dive

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

Set, Python's mutable collection of unique, unordered elements. Construction, all seventeen public set methods, the equivalent operators, and set…

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 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.

🧠 Test yourself

Pick an answer to check it. Your best score is saved in this browser.

  1. What does this print?

    print(type({}))
    
  2. What does this print?

    a = {1, 2, 3, 4}
    b = {3, 4, 5, 6}
    print(sorted(a ^ b))
    
  3. What is the difference between remove(x) and discard(x) when x is not in the set?

  4. What does this print?

    print(len(set('mississippi')))
    
  5. What does this print?

    a = {1, 2}
    b = {1, 2, 3}
    print(a <= b, a.isdisjoint(b))
    

💻 Practice exercises

Try each one in the notebook or in your own editor before opening the solution.

  1. Remove duplicates from [3, 1, 3, 2, 1] and print the unique values in sorted order.

    💡 Hint

    Wrap the list in set() and then use sorted().

    ✅ Show solution
    nums = [3, 1, 3, 2, 1]
    print(sorted(set(nums)))
    
  2. Two classes have students lists. Print who is in both, who is only in class A, and everyone combined (each as a sorted list).

    💡 Hint

    Use the & , - and | operators on sets.

    ✅ Show solution
    class_a = ["Ana", "Sam", "Lee", "Kim"]
    class_b = ["Sam", "Kim", "Raj"]
    a, b = set(class_a), set(class_b)
    print(sorted(a & b))   # both
    print(sorted(a - b))   # only A
    print(sorted(a | b))   # everyone
    
  3. Write find_duplicates(items) that returns the set of values appearing more than once, using a 'seen' set in a single pass. Then write is_pangram(text) using a set of letters.

    💡 Hint

    Track seen items; if an item is already seen, add it to the duplicates set. For the pangram, compare letters to set('abcdefghijklmnopqrstuvwxyz').

    ✅ Show solution
    import string
    
    def find_duplicates(items):
        seen, dupes = set(), set()
        for item in items:
            if item in seen:
                dupes.add(item)
            else:
                seen.add(item)
        return dupes
    
    def is_pangram(text):
        letters = {c for c in text.lower() if c.isalpha()}
        return letters >= set(string.ascii_lowercase)
    
    print(find_duplicates([1, 2, 3, 2, 4, 1]))
    assert find_duplicates([1, 2, 3, 2, 4, 1]) == {1, 2}
    assert is_pangram("The quick brown fox jumps over the lazy dog")
    assert not is_pangram("hello world")
    

Found this useful?

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