Sets — Unordered Collections
862 words
4 min read
Visual companion
Python
Type and operator map
Python Week 1: the first filter for runtime behavior
View
Revision summary
What this note is really saying
Short form
# Sets — Unordered Collections > **Why read this?** Need to remove duplicates from a list? Check if items exist in one collection but not another?

Sets — Unordered Collections
Why read this? Need to remove duplicates from a list? Check if items exist in one collection but not another? Find common elements between two groups? Sets are the right tool — they're optimized for membership testing and mathematical set operations.
🎯 Learning Objectives
By the end of this topic, you will be able to:
- Create sets with
{}andset() - Perform set operations: union, intersection, difference, symmetric difference
- Test membership efficiently
- Remove duplicates from sequences
- Understand when to use sets vs lists vs tuples
📋 Prerequisites
- Basic understanding of collections (lists, tuples).
📖 Core Content
17.1 What Problem Do Sets Solve?
Intuition: A set is like a bag where each item can appear only once. It doesn't remember order. It's incredibly fast at checking "is this item in the bag?" — much faster than a list for large collections.
17.2 Creating Sets
python# runnable # Using curly braces fruits = {"apple", "banana", "cherry"} print(fruits) # Using set() constructor numbers = set([1, 2, 3, 2, 1]) # duplicates removed! print(numbers) # {1, 2, 3} # From string chars = set("hello") print(chars) # {'h', 'e', 'l', 'o'} (duplicate l removed) # Empty set — must use set(), not {} empty_set = set() empty_dict = {} print(type(empty_set)) # <class 'set'> print(type(empty_dict)) # <class 'dict'>
17.3 Set Operations
python# runnable a = {1, 2, 3, 4, 5} b = {4, 5, 6, 7, 8} # Union — all elements from both print("Union:", a | b) # {1, 2, 3, 4, 5, 6, 7, 8} print("Union:", a.union(b)) # Intersection — common elements print("Intersection:", a & b) # {4, 5} print("Intersection:", a.intersection(b)) # Difference — in a but not in b print("Difference (a-b):", a - b) # {1, 2, 3} print("Difference (b-a):", b - a) # {8, 6, 7} # Symmetric difference — in either but not both print("Symmetric diff:", a ^ b) # {1, 2, 3, 6, 7, 8}
17.4 Set Methods
python# runnable s = {1, 2, 3} # Add elements s.add(4) print("After add:", s) # Remove (error if missing) s.remove(3) print("After remove:", s) # Discard (no error if missing) s.discard(10) # no error print("After discard:", s) # Pop (remove arbitrary element) popped = s.pop() print(f"Popped: {popped}, Remaining: {s}") # Clear s.clear() print("After clear:", s) # Subset, superset checks a = {1, 2} b = {1, 2, 3, 4} print("a is subset of b:", a.issubset(b)) # True print("b is superset of a:", b.issuperset(a)) # True print("Disjoint:", a.isdisjoint({5, 6})) # True
17.5 Membership Testing — Sets Are Fast!
python# runnable import time # Create large collection n = 10_000_000 big_list = list(range(n)) big_set = set(range(n)) # Time membership test start = time.time() print(9999999 in big_list) print(f"List membership: {time.time() - start:.3f}s") start = time.time() print(9999999 in big_set) print(f"Set membership: {time.time() - start:.3f}s")
17.6 Worked Example 1: Remove Duplicates
python# runnable names = ["Alice", "Bob", "Alice", "Charlie", "Bob", "David"] unique_names = list(set(names)) print(f"Original: {names}") print(f"Unique: {unique_names}")
17.7 Worked Example 2: Find Common Elements
python# runnable course_a = {"Alice", "Bob", "Charlie", "Diana"} course_b = {"Bob", "Diana", "Eve", "Frank"} both = course_a & course_b either = course_a | course_b only_a = course_a - course_b only_b = course_b - course_a print(f"In both courses: {both}") print(f"In either course: {either}") print(f"Only in A: {only_a}") print(f"Only in B: {only_b}")
17.8 Worked Example 3: Pangram Checker
python# runnable def is_pangram(text): alphabet = set("abcdefghijklmnopqrstuvwxyz") letters = set(text.lower()) return alphabet.issubset(letters) print(is_pangram("The quick brown fox jumps over the lazy dog")) # True print(is_pangram("Hello World")) # False
17.9 Worked Example 4: Unique Vowels
python# runnable text = "Beautiful Python Programming" vowels = set("aeiou") letters = set(text.lower()) unique_vowels = letters & vowels print(f"Text: {text}") print(f"Unique vowels: {sorted(unique_vowels)}")
⚠️ Common Pitfalls
Pitfall 1: Using {} for Empty Set Creates Dict
The mistake:
s = {} intending to create an empty set, but it creates an empty dictionary. Fix: Use s = set() for an empty set.Pitfall 2: Sets Don't Support Indexing
The mistake:
s[0] on a set. Error: TypeError: 'set' object is not subscriptable Fix: Convert to list first if you need indexing: list(s)[0].Pitfall 3: Sets Only Hold Hashable Items
The mistake:
s = {[1, 2], [3, 4]} (list as set element). Error: TypeError: unhashable type: 'list' Fix: Use tuples instead: s = {(1, 2), (3, 4)}.📝 Practice Questions
Q1: What does set("abracadabra") return?Answer:{'a', 'b', 'r', 'c', 'd'}(each unique character, order not guaranteed) Q2: What's the difference between remove() and discard()?Answer:remove(x)raisesKeyErrorif x is not in the set.discard(x)does nothing if x is not in the set. Q3-10: Additional set questions.(Following the same pattern.)
🔗 Cross-References
- Next Topic: Strings — Advanced Methods
- Previous Topic: Tuples
- Reference: Python for Everybody, Chapter 8 (Section 8.7)
- Video: L53: Lists & sets, L60: More on sets Join Discord Previous16. TuplesNext18. Strings Advanced