Set Methods Reference
Deduplication and set math operators (intersections, unions).
Add element to set.
Used In: Deduplicating streaming IDs, tracking visited paths.
set.add(x)s = {1, 2}
s.add(2)
print(s){1, 2}Time Complexity: O(1)
Common Mistakes: Instantiating an empty set using s = {} actually creates an empty dict; use s = set() instead.
Related Methods: update(), discard()
add() vs update(): add(x) inserts a single element x into the set; update(iterable) inserts all elements from the iterable into the set.
Add all elements from an iterable to the set.
Used In: Batch record deduplication.
set.update(iterable)s = {1}
s.update([2, 3])
print(s){1, 2, 3}Time Complexity: O(K) where K is size of iterable
Related Methods: add()
Remove element from set; raise KeyError if missing.
Used In: Deleting active tags.
set.remove(x)s = {1, 2}
s.remove(1)
print(s){2}Time Complexity: O(1)
Related Methods: discard()
remove() vs discard(): remove() throws KeyError if the element is missing; discard() fails silently.
Remove element from set safely without throwing errors if missing.
Used In: Tearing down optional flag sets.
set.discard(x)s = {1, 2}
s.discard(3)
print(s){1, 2}Time Complexity: O(1)
Related Methods: remove()
Remove and return an arbitrary element from the set.
Used In: Consuming unique item streams.
set.pop()s = {10, 20}
v = s.pop()
print(type(v))<class 'int'>Time Complexity: O(1)
Related Methods: remove()
Return a new set containing elements from all sets.
Used In: Aggregating unique identifiers across lists.
set.union(*others)s1 = {1}
s2 = {2}
print(s1.union(s2)){1, 2}Time Complexity: O(S + T) where S, T are set sizes
Related Methods: update()
Get common elements between sets.
Used In: Finding overlapping keys, filtering datasets.
set.intersection(*others)s1 = {'a', 'b'}
s2 = {'b', 'c'}
print(s1.intersection(s2)){'b'}Time Complexity: O(min(len(s1), len(s2)))
Common Mistakes: Using operator & requires both operands to be sets, whereas method intersection() accepts any iterable.
Related Methods: union(), difference()
set.intersection() vs set.difference(): intersection() returns common elements; difference() returns elements present in s1 but absent in s2.
Return elements that exist in the set but not in others.
Used In: Finding missing keys, pipeline audit gaps.
set.difference(*others)s1 = {1, 2, 3}
s2 = {2}
print(s1.difference(s2)){1, 3}Time Complexity: O(len(s1))
Related Methods: intersection()
Check if all elements of the set exist in another set.
Used In: Validating categorical domains.
set.issubset(other){1, 2}.issubset({1, 2, 3})TrueTime Complexity: O(len(set))
Related Methods: issuperset()
Check if the set contains all elements of another set.
Used In: Schema matching validations.
set.issuperset(other){1, 2, 3}.issuperset({1, 2})TrueTime Complexity: O(len(other))
Related Methods: issubset()