DEV Community

SameerQaisar17
SameerQaisar17

Posted on

Python Sets and Tuples: When Lists Aren't Right

πŸ“Œ 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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output:

{'a@test.com','b@test.com','c@test.com'}
Enter fullscreen mode Exit fullscreen mode

One Line. No Loop. Done

4. The Solution (Tuples)

coordinates = (40.7128, -74.0060)
print(coordinates[0])
Enter fullscreen mode Exit fullscreen mode

Output:

40.7128
Enter fullscreen mode Exit fullscreen mode

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)   
Enter fullscreen mode Exit fullscreen mode

Output:

True
False
Enter fullscreen mode Exit fullscreen mode

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)