Sets

DATA STRUCTURES


Python Sets

A set in Python is an unordered collection of unique elements. It is useful when you need to store distinct items and perform fast membership checks. Sets are mutable, but the elements inside a set must be immutable (e.g., numbers, strings, tuples).

Good for: Unique elements, unordered, fast membership checks

Basic Operations

  • set.add(x) → Add an element
  • set.remove(x) → Remove (error if not found)
  • set.discard(x) → Remove (no error if not found)
  • set.pop() → Remove and return an arbitrary element
  • set.clear() → Remove all elements
  • set.copy() → Create a shallow copy

Set Operations

  • set1 | set2 or set1.union(set2) → Union (combine both sets)
  • set1 & set2 or set1.intersection(set2) → Intersection (common elements)
  • set1 - set2 or set1.difference(set2) → Difference (only in set1)
  • set1 ^ set2 or set1.symmetric_difference(set2) → Symmetric difference (elements in either but not both)

Membership & Comparisons

  • x in set → Check if x exists
  • set1.issubset(set2) → Check if set1 is a subset
  • set1.issuperset(set2) → Check if set1 is a superset

Conversion

  • set(list/tuple) → Convert list/tuple to set

Example Usage


# Creating a set
fruits = {"apple", "banana", "cherry"}

# Adding an element
fruits.add("orange")

# Removing an element safely
fruits.discard("banana")

# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}

union_set = set1 | set2  # {1, 2, 3, 4, 5}
intersection_set = set1 & set2  # {3}
difference_set = set1 - set2  # {1, 2}
symmetric_diff_set = set1 ^ set2  # {1, 2, 4, 5}

print(union_set, intersection_set, difference_set, symmetric_diff_set)