Sets
Sets are Python's unordered collections with no duplicate elements. They're perfect for removing duplicates, testing membership efficiently, and performing mathematical set operations like union, intersection, and difference. Think of them as mathematical sets from school!
Creating Sets
Sets are created with curly braces {} or the set() constructor.
Duplicates are automatically removed, and only immutable (hashable) items can be stored.
Click Run to execute your code
set(),
not {}. Empty curly braces {} create an empty dictionary, not a set!
This is one of Python's most common gotchas.
Adding and Removing Elements
Sets are mutable - you can add and remove elements. Use add() for single items,
update() for multiple items, and remove() or discard() to delete.
Click Run to execute your code
discard() instead of remove() when
you're not sure if an element exists. remove() raises a KeyError for missing
elements, while discard() silently does nothing.
Set Operations
Sets support mathematical operations: union (|), intersection (&), difference (-), and symmetric difference (^). These are powerful tools for comparing and combining data.
Click Run to execute your code
|,
&, -, ^) or methods (.union(),
.intersection(), etc.). Methods accept any iterable as argument, while
operators require both sides to be sets.
Practical Use Cases
Sets excel at removing duplicates, finding common elements, fast membership testing, and comparing datasets. Let's see some real-world examples.
Click Run to execute your code
Common Mistakes
1. Using {} for empty set
# Wrong - creates empty dict, not set!
empty = {}
print(type(empty)) #
# Correct
empty_set = set()
print(type(empty_set)) #
2. Trying to add mutable items
# Wrong - lists are mutable/unhashable
my_set = {[1, 2, 3]} # TypeError!
# Correct - use tuples instead
my_set = {(1, 2, 3)} # Works!
print(my_set)
3. Expecting order in sets
# Wrong assumption
my_set = {3, 1, 2}
first = list(my_set)[0] # NOT guaranteed to be 3!
# Sets are unordered - don't rely on element order
# Use sorted() if you need order
ordered = sorted(my_set)
print(ordered) # [1, 2, 3]
4. Using remove() without checking
# Wrong - raises KeyError if not found
my_set = {1, 2, 3}
my_set.remove(5) # KeyError: 5
# Correct - use discard() or check first
my_set.discard(5) # No error
# OR
if 5 in my_set:
my_set.remove(5)
Exercise: Guest List Manager
Task: Manage a party guest list using sets.
Requirements:
- Add "David" to the guest list
- Try adding "Alice" again (observe what happens)
- Remove "Bob" from the list
Click Run to execute your code
Show Solution
guests = {"Alice", "Bob", "Charlie"}
# Add David
guests.add("David")
print(f"After adding David: {guests}")
# Try adding Alice again - no duplicate!
guests.add("Alice")
print(f"After adding Alice again: {guests}")
# Remove Bob
guests.remove("Bob")
print(f"After removing Bob: {guests}")
Summary
- Creating: Use
{}with items, orset()for empty - Properties: Unordered, no duplicates, only hashable items
- Adding:
add()single,update()multiple - Removing:
remove()(error if missing),discard()(no error) - Union:
A | BorA.union(B) - Intersection:
A & BorA.intersection(B) - Difference:
A - BorA.difference(B) - Best for: Removing duplicates, fast membership testing, comparing datasets
What's Next?
Now let's explore Dictionaries - Python's powerful key-value data structure. Dictionaries let you store and retrieve data using descriptive keys instead of numeric indices!
Enjoying these tutorials?