Python Data Structures
Python Sets
A set is an unordered collection that automatically removes duplicates, making it the go-to structure whenever you only care about unique values.
Creating a Set
You create a set with curly braces or the set() function. Sets have no fixed order and cannot contain duplicate values — Python silently drops any repeats.
fruits = {"apple", "banana", "apple"}
print(fruits) # {'apple', 'banana'}
empty = set() # {} creates a dict, not a set!
nums = set([1, 2, 2, 3])
print(nums) # {1, 2, 3}Adding and Removing Items
add() inserts a single item; remove() deletes one, raising an error if it is missing, while discard() removes it silently if present. Because a set is unordered, you cannot access items by index.
colors = {"red", "green"}
colors.add("blue")
colors.discard("yellow") # no error even though it's not there
colors.remove("red")
print(colors)Set Operations
Sets support fast mathematical operations for comparing two collections — perfect for tasks like finding common tags, shared skills, or unique visitors.
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # union: {1, 2, 3, 4, 5, 6}
print(a & b) # intersection: {3, 4}
print(a - b) # difference: {1, 2}
print(a ^ b) # symmetric difference: {1, 2, 5, 6}Set Operation Reference
| Operation | Operator | Method | Result |
|---|---|---|---|
| Union | a | b | a.union(b) | All items from both sets |
| Intersection | a & b | a.intersection(b) | Items in both sets |
| Difference | a - b | a.difference(b) | Items only in a |
| Symmetric difference | a ^ b | a.symmetric_difference(b) | Items not shared by both |
Use a set to quickly remove duplicates from a list: unique_items = list(set(my_list)). Note this loses the original order.
