Intro

  • Python’s set is a hash table-based implementation of the Set ADT (each element is stored as a key with no associated values)

Creating Sets

  • Using curly braces
fruits = {"apple", "banana", "cherry"} # Note: fruits = ("apple", "banana", "cherry") creates a tuple
 
mixed_set = {4,3,2,3,5,1} # Duplicates removed -> {1, 2, 3, 4, 5}
  • Using the set() constructor
# Create an empty set 
empty_set = set() # Note: {} creates an empty dictionary
 
# Convert an iterable to a set
numbers_list = [1,1,2,3,4,4,5]
unique_numbers_set = set(numbers_list) # Duplicates removed -> {1, 2, 3, 4, 5}

Common Operations

s = {1,2,3}
s.add(4) # {1, 2, 3, 4}
s.remove(2) # {1, 3, 4}
print(3 in s) # True
  • Since sets are unordered, they have no indices, so you cannot access or assign by index
s[0] # TypeError: 'set' object is not subscriptable
s[0] = 4 # TypeError: 'set' object does not support item assignment

Mathematical Operations

A = {1, 2, 3}
B = {3, 4, 5}
 
A | B   # union → {1, 2, 3, 4, 5}
A & B   # intersection → {3}
A - B   # difference → {1, 2}