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

OperationSyntaxExampleResultDescription
Empty Setset()my_set = set()set()Create empty set (not {})
Set Literal{item1, item2, ...}{1, 2, 3}{1, 2, 3}Create set with items
Set from Iterableset(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
Lengthlen(set)len({1, 2, 3})3Get number of unique items
Membershipitem in set2 in {1, 2, 3}TrueCheck if item exists
Copyset.copy()new_set = my_set.copy()New setCreate shallow copy

Adding Elements Methods

MethodPurposeExampleResultDescription
add()Add single elements.add(4)Modifies setAdds element to set (no effect if already present)
update()Add multiple elementss.update([4, 5, 6])Modifies setAdds all elements from iterable

Removing Elements Methods

MethodPurposeExampleResultDescription
remove()Remove elements.remove(2)Modifies setRemoves element (raises KeyError if not found)
discard()Remove element safelys.discard(2)Modifies setRemoves element (no error if not found)
pop()Remove arbitrary elements.pop()Returns removed elementRemoves and returns arbitrary element
clear()Remove all elementss.clear()set()Empties the set

Mathematical Set Operations

Set Union (|, union())

OperationSyntaxExampleResultDescription
Union Operatorset1 | set2{1, 2} | {2, 3}{1, 2, 3}Elements in either set
Union Methodset1.union(set2){1, 2}.union({2, 3}){1, 2, 3}Elements in either set
Multiple Unionset1.union(set2, set3){1}.union({2}, {3}){1, 2, 3}Union of multiple sets
In-place Unionset1 |= set2s |= {4, 5}Modifies sUpdate with union

Set Intersection (&, intersection())

OperationSyntaxExampleResultDescription
Intersection Operatorset1 & set2{1, 2, 3} & {2, 3, 4}{2, 3}Elements in both sets
Intersection Methodset1.intersection(set2){1, 2, 3}.intersection({2, 3, 4}){2, 3}Elements in both sets
Multiple Intersectionset1.intersection(set2, set3){1, 2}.intersection({2}, {2, 3}){2}Common elements in all sets
In-place Intersectionset1 &= set2s &= {2, 3}Modifies sUpdate with intersection

Set Difference (-, difference())

OperationSyntaxExampleResultDescription
Difference Operatorset1 - set2{1, 2, 3} - {2, 3, 4}{1}Elements in set1 but not set2
Difference Methodset1.difference(set2){1, 2, 3}.difference({2, 3, 4}){1}Elements in set1 but not set2
Multiple Differenceset1.difference(set2, set3){1, 2, 3}.difference({2}, {3}){1}Elements not in any other set
In-place Differenceset1 -= set2s -= {2, 3}Modifies sUpdate with difference

Set Symmetric Difference (^, symmetric_difference())

OperationSyntaxExampleResultDescription
Symmetric Difference Operatorset1 ^ set2{1, 2, 3} ^ {2, 3, 4}{1, 4}Elements in either set, but not both
Symmetric Difference Methodset1.symmetric_difference(set2){1, 2, 3}.symmetric_difference({2, 3, 4}){1, 4}Elements in either set, but not both
In-place Symmetric Differenceset1 ^= set2s ^= {2, 3}Modifies sUpdate with symmetric difference

Set Comparison Methods

MethodPurposeExampleResultDescription
issubset()Check if subset{1, 2}.issubset({1, 2, 3})TrueTrue if all elements are in other set
issuperset()Check if superset{1, 2, 3}.issuperset({1, 2})TrueTrue if contains all elements of other set
isdisjoint()Check if disjoint{1, 2}.isdisjoint({3, 4})TrueTrue if no common elements

Set Comprehensions

TypeSyntaxExampleResultDescription
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

OperationAverage CaseWorst CaseNotes
Add/Remove/SearchO(1)O(n)Hash collision can cause O(n)
Union/IntersectionO(len(s) + len(t))O(len(s) * len(t))Depends on hash distribution
Subset/SupersetO(len(smaller_set))O(len(smaller_set))Check each element
IterationO(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?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent