What Is a Set?
A set is an unordered collection of unique items. Sets automatically remove duplicates and are written with curly braces {}.
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 2, 3, 3, 3}
print(numbers) # {1, 2, 3} — duplicates removed automatically
Creating a Set
empty_set = set() # NOT {} — that creates an empty dict!
fruits = set(["apple", "banana", "apple"])
print(fruits) # {'apple', 'banana'}
Adding and Removing Items
fruits = {"apple", "banana"}
fruits.add("cherry") # add a single item
fruits.update(["mango", "grape"]) # add multiple items
fruits.remove("banana") # removes item, errors if not found
fruits.discard("kiwi") # removes if present, no error if missing
Set Operations
Sets support mathematical set operations, which makes them powerful for comparing collections:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union → {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection → {3, 4}
print(a - b) # Difference → {1, 2}
print(a ^ b) # Symmetric difference → {1, 2, 5, 6}
Checking Membership
fruits = {"apple", "banana", "cherry"}
print("apple" in fruits) # True
print("mango" in fruits) # False
Membership checks in a set are much faster than in a list, especially for large collections.
Removing Duplicates from a List
A very common real-world use of sets:
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers) # [1, 2, 3, 4, 5]
Frozenset — An Immutable Set
frozen = frozenset([1, 2, 3])
# frozen.add(4) # ❌ Error — frozensets cannot be modified
Key Takeaways
- Sets store only unique items and have no guaranteed order
- Use
set()to create an empty set —{}creates an empty dictionary instead - Sets support union, intersection, difference, and symmetric difference operations
- A quick way to remove duplicates from a list is
list(set(my_list))