Set Operations

  • This lesson explains how to perform union, intersection, and other operations on Python sets.

  • Set Operations

    Set operations are used to perform mathematical operations like union, intersection, difference, etc.

Union (| or union())

Union combines elements from both sets and removes duplicates.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1 | set2
print(result)

Intersection (& or intersection())

Intersection returns common elements present in both sets.

set1 = {1, 2, 3}
set2 = {2, 3, 4}
result = set1 & set2
print(result)

Difference (- or difference())

Difference returns elements present in the first set but not in the second.

set1 = {1, 2, 3}
set2 = {2, 3, 4}
result = set1 - set2
print(result)

Symmetric Difference (^ or symmetric_difference())

Returns elements that are in either set but NOT in both.

set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1 ^ set2
print(result)

Subset (<=)

Checks if all elements of one set are inside another set.

a = {1, 2}
b = {1, 2, 3, 4}
print(a <= b)

Superset (>=)

Checks if a set contains all elements of another set.

a = {1, 2, 3, 4}
b = {1, 2}
print(a >= b)

Disjoint Sets

Two sets are disjoint if they have no common elements.

a = {1, 2}
b = {3, 4}
print(a.isdisjoint(b))