Welcome to Day 24 of the 100 Days of Python series!
Today we dive into a unique and powerful Python data structure: the set.
Sets are great when you want to store unique items, remove duplicates, or perform mathematical operations like unions, intersections, and differences.
Let’s explore how sets work and where to use them! 🐍
📦 What You’ll Learn
- What sets are and how to create them
- How sets differ from lists and tuples
- Built-in set methods
- Set operations: union, intersection, difference, symmetric difference
- Real-world use cases
🔹 1. What is a Set?
A set is an unordered, mutable, and unindexed collection that does not allow duplicate values.
🔹 Syntax:
my_set = {1, 2, 3}
You can also create an empty set using the set()
constructor:
empty_set = set()
⚠️
{}
creates an empty dictionary, not a set!
✅ 2. Why Use Sets?
- Automatically removes duplicates
- Great for membership testing (
in
) - Super efficient for mathematical operations
- Ideal for comparing groups of values
🔧 3. Basic Set Operations
Create a Set
fruits = {"apple", "banana", "cherry"}
Add Items
fruits.add("orange")
Remove Items
fruits.remove("banana") # Raises error if not found
fruits.discard("banana") # Safe removal (no error)
Clear All Items
fruits.clear()
Copy a Set
new_set = fruits.copy()
🔁 4. Set Looping
for fruit in fruits:
print(fruit)
Note: Since sets are unordered, the output may not follow insertion order.
🔀 5. Set Operations
Let’s take two sets:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
🔸 Union – All unique items
print(a | b) # {1, 2, 3, 4, 5, 6}
print(a.union(b)) # Same result
🔸 Intersection – Common items
print(a & b) # {3, 4}
print(a.intersection(b)) # Same result
🔸 Difference – Items in A but not in B
print(a - b) # {1, 2}
print(a.difference(b)) # Same result
🔸 Symmetric Difference – Items in A or B, but not both
print(a ^ b) # {1, 2, 5, 6}
print(a.symmetric_difference(b)) # Same
🔎 6. Membership Testing
print(3 in a) # True
print(10 in a) # False
This is faster in sets than in lists!
⚠️ 7. Sets vs Other Collections
Feature | List | Tuple | Set |
---|---|---|---|
Ordered | ✅ | ✅ | ❌ |
Mutable | ✅ | ❌ | ✅ |
Allows Duplicates | ✅ | ✅ | ❌ |
Indexable | ✅ | ✅ | ❌ |
Fast Membership | ❌ | ❌ | ✅ |
🧪 Real-World Examples
1. Removing Duplicates from a List
nums = [1, 2, 2, 3, 4, 4, 5]
unique_nums = list(set(nums))
print(unique_nums) # [1, 2, 3, 4, 5]
2. Checking Common Interests
alice_hobbies = {"reading", "coding", "traveling"}
bob_hobbies = {"coding", "gaming"}
common = alice_hobbies & bob_hobbies
print(common) # {'coding'}
3. Unique Words in a Sentence
sentence = "this is a test this is only a test"
unique_words = set(sentence.split())
print(unique_words)
🧠 Recap
Today you learned:
- What sets are and how to create and modify them
- That sets remove duplicates and speed up membership tests
- Set operations: union, intersection, difference, and more
- Real-world examples using sets for cleaning and comparison