What are Sets?
A Set is an unordered collection of unique items. If you put duplicate items into a set, Python automatically throws away the extras and keeps only one copy.
Think of a set like:
- A bowl of different fruit flavors (no two candies are the exact same flavor)
- A guest list where people who RSVP twice are only listed once
Creating Sets
You create a set using curly braces {} with items inside, or by using the set() function:
# A set of colors
colors = {"red", "blue", "green", "red"}
# Notice that the duplicate "red" disappears automatically!
print(colors) # Output: {'blue', 'green', 'red'}
Empty Set Trap
To create an empty set, you must use set(). Typing {} creates an empty Python Dictionary instead!
# Wrong - creates an empty dictionary
wrong_set = {}
print(type(wrong_set)) # <class 'dict'>
# Right - creates an empty set
clean_set = set()
print(type(clean_set)) # <class 'set'>
Removing Duplicates from a List
The most common real-world use case for a set is cleaning up duplicates from a list:
raw_emails = ["user@test.com", "admin@test.com", "user@test.com"]
# Convert to a set to drop duplicates, then back to a list
clean_emails = list(set(raw_emails))
print(clean_emails) # Output: ['user@test.com', 'admin@test.com']
Sets Have No Index Numbers
Because sets store items in an unordered way, there is no index 0 or index 1. You cannot grab items using brackets []:
fruits = {"apple", "banana"}
# print(fruits[0]) # TypeError: 'set' object is not subscriptable
Adding and Removing Items (add, remove, discard)
.add(item)adds a single new item..remove(item)removes an item, but throws an error if the item is not found..discard(item)safely removes an item without throwing an error if it is missing.
tags = {"python", "ai"}
tags.add("data")
print(tags) # Output: {'python', 'data', 'ai'}
tags.discard("java") # Safe! No error raised even though "java" isn't inside.
Common Beginner Mistakes
- No Indexing: Sets have no fixed order or index positions.
numbers[0]raisesTypeError: 'set' object is not subscriptable. - Empty Set Creation: Writing
{}creates an empty dictionary. Always writes = set()to create an empty set.
Quick Summary
- Set Definition: An unordered collection of unique elements enclosed in curly braces
{...}. - Automatic Deduplication: Duplicate items are discarded automatically (
set([1, 2, 2, 3])->{1, 2, 3}). - Fast Membership: Checking
item in my_setruns in $O(1)$ constant time, much faster than lists. - Modifying Elements: Use
.add()to insert,.remove()to delete with error on missing, or.discard()to remove safely.
What's Next?
Let's explore mathematical set operations like combining sets (union), finding overlaps (intersection), and finding differences!