Python Sets: The Complete Guide
Learn why professional Python developers love Sets for removing duplicates and calculating intersections instantly.
What is a Python Set?
A Set is an unordered collection of unique elements. It is defined by
curly braces {} or the set() constructor.
Key Features
- Unordered: Items have no index. You cannot access them like
set[0]. - Unique: No duplicates allowed. Adding a duplicate does nothing.
- Mutable: You can add and remove items after creation.
- Fast: Checking if an item is in a set is O(1) (instant), compared to O(n) for lists.
Basic Operations
Creating a Set
# Direct creation
my_set = {1, 2, 3, 3, 3}
print(my_set)
# Output: {1, 2, 3} (Duplicates removed automatically)
# From a list
my_list = ["apple", "banana", "apple"]
fruit_set = set(my_list)
print(fruit_set)
# Output: {'banana', 'apple'}
Adding and Removing
s = {1, 2, 3}
# Add
s.add(4)
# Remove (Raises error if missing)
s.remove(2)
# Discard (No error if missing)
s.discard(99)
Set Mathematics (Venn Diagrams)
This is where sets shine. You can perform standard mathematical operations.
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
# Union (All items in both) |
print(A | B)
# Output: {1, 2, 3, 4, 5, 6}
# Intersection (Only common items) &
print(A & B)
# Output: {3, 4}
# Difference (In A but NOT in B) -
print(A - B)
# Output: {1, 2}
# Symmetric Difference (In A or B, but NOT both) ^
print(A ^ B)
# Output: {1, 2, 5, 6}
When to use a Set vs List?
Use a Set when:
- You need to ensure all items are unique.
- You need to check for existence often (e.g.,
if user_id in banned_ids:). - Order does not matter.
Use a List when:
- Order matters (e.g., a timeline or ranking).
- You allow duplicates.
- You need to access items by index.