Set Basics
Sets are unordered collections of unique elements. They are mutable, but every element must be hashable (immutable).
Creating Sets
s1 = {1, 2, 3, 4}
s2 = set([1, 2, 2, 3, 3, 4]) # duplicates removed
print(s2) # {1, 2, 3, 4}
empty_set = set() # NOT {} — that creates a dict!add() & discard() / remove()
fruits = {"apple", "banana", "cherry"}
fruits.add("mango")
fruits.add("apple") # no duplicate added
print(fruits)
fruits.discard("banana") # no error if missing
fruits.remove("cherry") # raises KeyError if missing
fruits.discard("kiwi") # safe — does nothingMembership Testing
# Sets use O(1) hash lookup — much faster than lists
print("mango" in fruits) # True
print("grape" not in fruits) # TrueIterating
for fruit in sorted(fruits):
print(fruit)