Python Sets & Set Operations
In Python, a set is a built-in data structure used to store an unordered, unindexed, and mutable collection of unique elements. Because elements cannot be duplicated, sets are extremely useful for membership testing, removing duplicates from sequences, and performing mathematical set operations like unions and intersections.
1. Creating Sets
You can create a set by enclosing comma-separated values in curly braces {} or by using the built-in set() constructor.
# Creating a set with curly braces
fruits = {"apple", "banana", "cherry"}
print(fruits) # Output order may vary: {'banana', 'cherry', 'apple'}
# Creating a set from a list (automatically removes duplicates)
numbers_list = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = set(numbers_list)
print(unique_numbers) # {1, 2, 3, 4, 5}
# Creating an empty set (Note: {} creates an empty dictionary, use set())
empty_set = set()
2. Adding and Removing Elements
Since sets are mutable, you can modify their contents, but you cannot modify individual items directly (because they have no indexes).
| Operation | Method / Syntax | Description |
|---|---|---|
| Add single item | s.add(item) |
Adds an element to the set. If it already exists, nothing happens. |
| Add multiple items | s.update(iterable) |
Updates the set with elements from another set, list, or tuple. |
| Remove item (Strict) | s.remove(item) |
Removes an element. Raises a KeyError if the item is not found. |
| Remove item (Safe) | s.discard(item) |
Removes an element. Does not raise an error if the item is missing. |
| Remove random item | s.pop() |
Removes and returns an arbitrary element from the set. |
| Clear set | s.clear() |
Removes all elements from the set. |
colors = {"red", "green"}
# Adding elements
colors.add("blue")
colors.update(["yellow", "purple"])
print(colors) # {'red', 'green', 'blue', 'yellow', 'purple'}
# Removing elements
colors.remove("green")
colors.discard("orange") # Safe: won't crash even though 'orange' isn't there
print(colors)
3. Mathematical Set Operations
Python provides intuitive operators and methods to perform standard set theory operations.
A. Union (Combining Sets)
Returns all unique elements from both sets. Can be done using the | operator or .union().
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_result = set_a | set_b
# Or: union_result = set_a.union(set_b)
print(union_result) # {1, 2, 3, 4, 5}
B. Intersection (Common Elements)
Returns only the elements present in both sets using & or .intersection().
intersection_result = set_a & set_b
# Or: intersection_result = set_a.intersection(set_b)
print(intersection_result) # {3}
C. Difference (Elements in A but not B)
Returns elements present in the first set but absent in the second using - or .difference().
difference_result = set_a - set_b
# Or: difference_result = set_a.difference(set_b)
print(difference_result) # {1, 2}
D. Symmetric Difference (Exclusive Elements)
Returns elements that are in either set, but not in both using ^ or .symmetric_difference().
sym_diff = set_a ^ set_b
print(sym_diff) # {1, 2, 4, 5}
4. Set Membership & Relationship Methods
| Method / Operator | Description | Example |
|---|---|---|
item in set |
Check if an item exists | "apple" in fruits |
issubset() or <= |
Check if all elements of A are in B | set_a.issubset(set_b) |
issuperset() or >= |
Check if all elements of B are in A | set_a.issuperset(set_b) |
isdisjoint() |
Returns True if two sets have no common elements |
set_a.isdisjoint(set_b) |
5. Frozenset (Immutable Sets)
A frozenset is an immutable version of a Python set. Once created, you cannot add or remove elements, making them hashable and usable as dictionary keys or elements of another set.
fs = frozenset([1, 2, 3])
# fs.add(4) # Raises AttributeError: 'frozenset' object has no attribute 'add'