Sets are collections that store unique items with no duplicates. They are useful for membership testing and removing duplicates quickly.
What is a set?
A set is created with curly braces {} and items separated by commas. Order does not matter.
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
mixed = {10, "hello", True}
You can also create a set from a list:
unique_numbers = set([1, 2, 2, 3, 3, 3])
print(unique_numbers) # {1, 2, 3}
An empty set (note: {} makes a dictionary):
empty_set = set()
Sets automatically remove duplicates.
Adding and removing items
Add an item with add():
fruits.add("orange")
print(fruits) # Includes orange
Remove an item with remove() (raises error if not found) or discard() (no error):
fruits.remove("banana")
fruits.discard("missing") # No error
Common operations
Check membership:
print("apple" in fruits) # True or False
Get length:
print(len(fruits)) # Number of unique items
Loop over a set:
for fruit in fruits:
print(fruit)
Set operations
Union (all items):
set1 = {1, 2, 3}
set2 = {3, 4, 5}
combined = set1.union(set2) # or set1 | set2
print(combined) # {1, 2, 3, 4, 5}
Intersection (common items):
common = set1.intersection(set2) # or set1 & set2
print(common) # {3}
Difference (items in one but not both):
diff = set1.difference(set2) # or set1 - set2
print(diff) # {1, 2}
Simple examples
Remove duplicates from a list:
scores = [85, 92, 85, 78, 92]
unique_scores = set(scores)
print(unique_scores) # {85, 92, 78}
Check common friends:
friends_a = {"Ali", "Sara", "Reza"}
friends_b = {"Sara", "Mohammad", "Reza"}
common = friends_a & friends_b
print(common) # {"Sara", "Reza"}
Important notes
- Sets are unordered: items have no index.
- Sets are mutable, but items must be immutable (no lists inside sets).
- Sets are fast for checking if an item exists.
Quick summary
- Create sets with curly braces or
set(). - Sets store unique items only.
- Use
add(),remove(), anddiscard()to modify. - Perform union, intersection, and difference easily.
- Ideal for removing duplicates and membership tests.
Practice using sets for unique collections. They provide efficient operations not available with lists in Python programs.
Top comments (0)