Beginner Fundamentals
Sets
A set is an unordered collection with no duplicates. It uses braces {}.
numbers = {1, 2, 3, 3, 2}
print(numbers) # {1, 2, 3} — duplicates removed
Add and remove
numbers.add(4)
numbers.discard(1)
No indexing
Sets aren’t ordered, so numbers[0] errors. Iterate with for:
for n in numbers:
print(n)
Set operations
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union: {1, 2, 3, 4, 5}
print(a & b) # intersection: {3}
print(a - b) # difference: {1, 2}
Common use: remove duplicates
items = [1, 1, 2, 3, 3]
unique = list(set(items)) # [1, 2, 3]
Empty set
empty = set() # {} creates a dict, not a set