Sobes.tech
Junior

What operations can be performed on sets in Python?

sobes.tech AI

Answer from AI

  • union
  • intersection
  • difference
  • symmetric difference
  • issubset
  • issuperset
  • isdisjoint
# Operation examples
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

# Union
union_set = set1 | set2 # or set1.union(set2)
# {1, 2, 3, 4, 5, 6}

# Intersection
intersection_set = set1 & set2 # or set1.intersection(set2)
# {3, 4}

# Difference
difference_set = set1 - set2 # or set1.difference(set2)
# {1, 2}

# Symmetric Difference
symmetric_difference_set = set1 ^ set2 # or set1.symmetric_difference(set2)
# {1, 2, 5, 6}

# Issubset
is_subset = {1, 2}.issubset(set1)
# True

# Issuperset
is_superset = set1.issuperset({1, 2})
# True

# Isdisjoint
is_disjoint = {1, 2}.isdisjoint({3, 4})
# True

Table of operations and their symbolic representations:

Operation Method Symbol
Union union() `
Intersection intersection() &
Difference difference() -
Symmetric Difference symmetric_difference() ^