π Quick Info
- Topic: Sets and Tuples in Python
- Target Audience: Beginners who know lists and dictionaries
- Goal: Understand when to use sets vs tuples vs lists
1. Introduction
"I thought lists were enough. Then I had a list of 10,000 emails and needed to check for duplicates. And another time I needed to make sure a value never changed. That's when I learned about sets and tuples."
2. The Problem (Using Lists for Everything)
emails = ["a@test.com", "b@test.com", "a@test.com", "c@test.com"]
# Finding duplicates manually
unique = []
for email in emails:
if email not in unique:
unique.append(email)
print(unique)
Problem: Works, But slow and messy. Python has a better tool.
3. The Solution (Sets)
emails = ["a@test.com", "b@test.com", "a@test.com", "c@test.com"]
unique_emails = set(emails)
print(unique_emails)
Output:
{'a@test.com','b@test.com','c@test.com'}
One Line. No Loop. Done
4. The Solution (Tuples)
coordinates = (40.7128, -74.0060)
print(coordinates[0])
Output:
40.7128
Tuples are like lists-but unchangeable.
5. Sets vs Tuples vs Lists: When to Use Which
| Type | Ordered? | Changeable? | Duplicates | Best for |
|---|---|---|---|---|
| Lists | Yes | Yes | Allowed | More things |
| Tuple | Yes | No | Allowed | Fixed Data |
| Set | No | Yes | No Duplicates | Removing Duplicates |
6. Real Examples (My Practice)
admin_emails = {"admin@site.com", "owner@site.com"}
print("admin@site.com" in admin_emails)
print("user@site.com" in admin_emails)
Output:
True
False
7. What I Learned
- Sets remove duplicates automatically
- Sets are unordered- you canβt rely on position
- Tuples canβt be changed after creation
- Tuples are faster than lists for fixed data
- Use Lists by Default, and reach for sets/tuples when you have a specific reason
8. Conclusion
βLists are still my go-to. But now I know: if I need uniqueness, use a set. If I need something That never changes, use a tuple. Right Tool, Right Job.β
Top comments (0)