Set Operations

Sets support powerful mathematical operations for combining and comparing collections.

Union

Combine all elements from both sets.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Using operator
union = set1 | set2
print(union)  # {1, 2, 3, 4, 5}

# Using method
union = set1.union(set2)
const set1 = new Set([1, 2, 3]);
const set2 = new Set([3, 4, 5]);

const union = new Set([...set1, ...set2]);
console.log(union); // Set {1, 2, 3, 4, 5}

Intersection

Find common elements.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Using operator
intersection = set1 & set2
print(intersection)  # {3, 4}

# Using method
intersection = set1.intersection(set2)
const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([3, 4, 5, 6]);

const intersection = new Set([...set1].filter((x) => set2.has(x)));
console.log(intersection); // Set {3, 4}

Difference

Elements in first set but not in second.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Using operator
diff = set1 - set2
print(diff)  # {1, 2}

# Using method
diff = set1.difference(set2)
const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([3, 4, 5, 6]);

const difference = new Set([...set1].filter((x) => !set2.has(x)));
console.log(difference); // Set {1, 2}

Symmetric Difference

Elements in either set, but not in both.

set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Using operator
sym_diff = set1 ^ set2
print(sym_diff)  # {1, 2, 5, 6}

# Using method
sym_diff = set1.symmetric_difference(set2)
const set1 = new Set([1, 2, 3, 4]);
const set2 = new Set([3, 4, 5, 6]);

const symDiff = new Set([
  ...[...set1].filter((x) => !set2.has(x)),
  ...[...set2].filter((x) => !set1.has(x)),
]);
console.log(symDiff); // Set {1, 2, 5, 6}

Subset and Superset

set1 = {1, 2}
set2 = {1, 2, 3, 4}

# Subset
print(set1.issubset(set2))    # True
print(set1 <= set2)           # True

# Proper subset
print(set1 < set2)            # True

# Superset
print(set2.issuperset(set1))  # True
print(set2 >= set1)           # True

Disjoint Sets

Check if sets have no elements in common.

set1 = {1, 2, 3}
set2 = {4, 5, 6}
set3 = {3, 4, 5}

print(set1.isdisjoint(set2))  # True
print(set1.isdisjoint(set3))  # False

Practical Examples

Find Common Friends

def common_friends(user1_friends, user2_friends):
    return user1_friends & user2_friends

alice_friends = {'Bob', 'Charlie', 'David'}
bob_friends = {'Alice', 'Charlie', 'Eve'}

common = common_friends(alice_friends, bob_friends)
print(common)  # {'Charlie'}

Find Missing Numbers

def find_missing(nums, n):
    """Find missing numbers from 1 to n"""
    complete = set(range(1, n + 1))
    present = set(nums)
    return complete - present

nums = [1, 2, 4, 6]
print(find_missing(nums, 6))  # {3, 5}

Find Unique Characters

def unique_chars_in_both(str1, str2):
    """Characters that appear in both strings"""
    return set(str1) & set(str2)

print(unique_chars_in_both("hello", "world"))
# {'l', 'o'}

Category Filtering

def filter_by_categories(items, required, excluded):
    """Filter items by required and excluded categories"""
    item_cats = set(items)

    # Must have all required
    if not required.issubset(item_cats):
        return False

    # Must not have any excluded
    if not item_cats.isdisjoint(excluded):
        return False

    return True

item = {'electronics', 'smartphone', 'sale'}
required = {'electronics'}
excluded = {'refurbished'}

print(filter_by_categories(item, required, excluded))
# True

Performance Considerations

All set operations are efficient:

OperationTime Complexity
UnionO(m + n)
IntersectionO(min(m, n))
DifferenceO(m)
Symmetric DiffO(m + n)
Subset CheckO(m)

Where m and n are the sizes of the sets.