Set Operations
Complete reference for Python set operations and methods. Sets are mutable, unordered collections of unique elements that provide efficient membership testing and mathematical set operations.
Set Creation and Basic Operations
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Empty Set | set() | my_set = set() | set() | Create empty set (not {} ) |
Set Literal | {item1, item2, ...} | {1, 2, 3} | {1, 2, 3} | Create set with items |
Set from Iterable | set(iterable) | set([1, 2, 2, 3]) | {1, 2, 3} | Convert iterable to set (removes duplicates) |
Set Comprehension | {expr for item in iterable} | {x*2 for x in range(3)} | {0, 2, 4} | Create set with expression |
Length | len(set) | len({1, 2, 3}) | 3 | Get number of unique items |
Membership | item in set | 2 in {1, 2, 3} | True | Check if item exists |
Copy | set.copy() | new_set = my_set.copy() | New set | Create shallow copy |
Adding Elements Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
add() | Add single element | s.add(4) | Modifies set | Adds element to set (no effect if already present) |
update() | Add multiple elements | s.update([4, 5, 6]) | Modifies set | Adds all elements from iterable |
Removing Elements Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
remove() | Remove element | s.remove(2) | Modifies set | Removes element (raises KeyError if not found) |
discard() | Remove element safely | s.discard(2) | Modifies set | Removes element (no error if not found) |
pop() | Remove arbitrary element | s.pop() | Returns removed element | Removes and returns arbitrary element |
clear() | Remove all elements | s.clear() | set() | Empties the set |
Mathematical Set Operations
Set Union (|, union())
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Union Operator | set1 | set2 | {1, 2} | {2, 3} | {1, 2, 3} | Elements in either set |
Union Method | set1.union(set2) | {1, 2}.union({2, 3}) | {1, 2, 3} | Elements in either set |
Multiple Union | set1.union(set2, set3) | {1}.union({2}, {3}) | {1, 2, 3} | Union of multiple sets |
In-place Union | set1 |= set2 | s |= {4, 5} | Modifies s | Update with union |
Set Intersection (&, intersection())
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Intersection Operator | set1 & set2 | {1, 2, 3} & {2, 3, 4} | {2, 3} | Elements in both sets |
Intersection Method | set1.intersection(set2) | {1, 2, 3}.intersection({2, 3, 4}) | {2, 3} | Elements in both sets |
Multiple Intersection | set1.intersection(set2, set3) | {1, 2}.intersection({2}, {2, 3}) | {2} | Common elements in all sets |
In-place Intersection | set1 &= set2 | s &= {2, 3} | Modifies s | Update with intersection |
Set Difference (-, difference())
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Difference Operator | set1 - set2 | {1, 2, 3} - {2, 3, 4} | {1} | Elements in set1 but not set2 |
Difference Method | set1.difference(set2) | {1, 2, 3}.difference({2, 3, 4}) | {1} | Elements in set1 but not set2 |
Multiple Difference | set1.difference(set2, set3) | {1, 2, 3}.difference({2}, {3}) | {1} | Elements not in any other set |
In-place Difference | set1 -= set2 | s -= {2, 3} | Modifies s | Update with difference |
Set Symmetric Difference (^, symmetric_difference())
Operation | Syntax | Example | Result | Description |
---|---|---|---|---|
Symmetric Difference Operator | set1 ^ set2 | {1, 2, 3} ^ {2, 3, 4} | {1, 4} | Elements in either set, but not both |
Symmetric Difference Method | set1.symmetric_difference(set2) | {1, 2, 3}.symmetric_difference({2, 3, 4}) | {1, 4} | Elements in either set, but not both |
In-place Symmetric Difference | set1 ^= set2 | s ^= {2, 3} | Modifies s | Update with symmetric difference |
Set Comparison Methods
Method | Purpose | Example | Result | Description |
---|---|---|---|---|
issubset() | Check if subset | {1, 2}.issubset({1, 2, 3}) | True | True if all elements are in other set |
issuperset() | Check if superset | {1, 2, 3}.issuperset({1, 2}) | True | True if contains all elements of other set |
isdisjoint() | Check if disjoint | {1, 2}.isdisjoint({3, 4}) | True | True if no common elements |
Set Comprehensions
Type | Syntax | Example | Result | Description |
---|---|---|---|---|
Basic | {expr for item in iterable} | {x**2 for x in range(5)} | {0, 1, 4, 9, 16} | Create set from expression |
With Condition | {expr for item in iterable if condition} | {x for x in range(10) if x % 2 == 0} | {0, 2, 4, 6, 8} | Filter with condition |
Nested | {expr for item in iterable for subitem in item} | {char for word in ['hello', 'world'] for char in word} | {'h', 'e', 'l', 'o', 'w', 'r', 'd'} | Flatten structures |
Performance Considerations
Time Complexity
Operation | Average Case | Worst Case | Notes |
---|---|---|---|
Add/Remove/Search | O(1) | O(n) | Hash collision can cause O(n) |
Union/Intersection | O(len(s) + len(t)) | O(len(s) * len(t)) | Depends on hash distribution |
Subset/Superset | O(len(smaller_set)) | O(len(smaller_set)) | Check each element |
Iteration | O(n) | O(n) | Must visit all elements |
Performance Tips
# Efficient membership testing
# Bad: using list for frequent membership tests
def slow_check(item, items_list):
return item in items_list # O(n) for each check
# Good: convert to set for frequent membership tests
def fast_check(item, items_set):
return item in items_set # O(1) for each check
# Convert once, use many times
items_list = [1, 2, 3, 4, 5] * 1000 # Large list
items_set = set(items_list) # Convert once
# Multiple membership tests are now fast
for i in range(100):
if i in items_set: # Fast O(1) lookup
pass
# Set operations are generally faster than manual loops
# Bad: manual intersection
def manual_intersection(list1, list2):
result = []
for item in list1:
if item in list2:
result.append(item)
return result
# Good: use set intersection
def set_intersection(list1, list2):
return list(set(list1) & set(list2))
Best Practices
- Use sets for membership testing: Much faster than lists for
in
operations - Remove duplicates efficiently: Convert to set and back to list
- Use set operations: More readable than manual loops for common operations
- Consider frozenset for immutable data: When you need hashable sets
- Be careful with mutable elements: Sets can only contain hashable (immutable) elements
- Use set comprehensions: More readable and often faster than loops
- Choose appropriate data structure: Sets for uniqueness, lists for order, dicts for key-value
- Leverage mathematical operations: Union, intersection, difference for data analysis
Was this helpful?
Track Your Learning Progress
Sign in to bookmark tutorials and keep track of your learning journey.
Your progress is saved automatically as you read.