
🐍 Lesson 14: Python Sets
1. What is a set?
In short → A set is an unordered, unindexed collection, and it doesn't allow duplicate values.
More formally → A set is an unordered, unindexed collection that does not allow duplicate values.
2. Set Operations
- Union (|) → combines two sets
- Intersection (&) → values that appear in both
- Difference (-) → values that appear in only one
3. Summary
✅ Set = unordered + unindexed + no duplicates
✅ Add values with add(), update()
✅ Remove values with remove(), discard(), pop(), clear()
✅ Set operations → Union, Intersection, Difference
python
# ===== 1. Create a Set =====
fruits = {"apple", "banana", "cherry"}
print(f"Set: {fruits}")
print(f"Type: {type(fruits)}")
# ===== 2. No Duplicates =====
print(f"\n===== No Duplicates =====")
nums = {1, 2, 2, 3, 4}
print(f"Set with duplicates: {nums}") # {1, 2, 3, 4}
# ===== 3. Add Items =====
print(f"\n===== Adding Items =====")
fruits.add("orange")
print(f"After add: {fruits}")
fruits.update(["mango", "grape"])
print(f"After update: {fruits}")
# ===== 4. Remove Items =====
print(f"\n===== Removing Items =====")
fruits.remove("apple") # Error if not found
print(f"After remove: {fruits}")
fruits.discard("banana") # No error if not found
print(f"After discard: {fruits}")
# ===== 5. Set Operations =====
print(f"\n===== Set Operations =====")
a = {1, 2, 3}
b = {3, 4, 5}
print(f"a | b (Union): {a | b}")
print(f"a & b (Intersection): {a & b}")
print(f"a - b (Difference): {a - b}")
print(f"a ^ b (Symmetric Diff): {a ^ b}")
# ===== 6. Loop Through Set =====
print(f"\n===== Looping =====")
for item in {"apple", "banana", "cherry"}:
print(item)
# ===== 7. Length =====
print(f"\nLength: {len(fruits)}")You should see
Set: {'cherry', 'apple', 'banana'} Type: ===== No Duplicates ===== Set with duplicates: {1, 2, 3, 4} ===== Adding Items ===== After add: {'cherry', 'orange', 'apple', 'banana'} After update: {'mango', 'cherry', 'orange', 'grape', 'apple', 'banana'} ===== Removing Items ===== After remove: {'mango', 'cherry', 'orange', 'grape', 'banana'} After discard: {'mango', 'cherry', 'orange', 'grape'} ===== Set Operations ===== a | b (Union): {1, 2, 3, 4, 5} a & b (Intersection): {3} a - b (Difference): {1, 2} a ^ b (Symmetric Diff): {1, 2, 4, 5} ===== Looping ===== apple banana cherry Length: 4