
Python
Learning Level
Sets automatically prevent duplicates and excel at checking membership and finding unique items.
A set stores unique values in curly braces, with no specific order.
# Create a set
colors = {"red", "green", "blue"}
# Set from a list (removes duplicates)
numbers = [1, 2, 2, 3, 3, 3, 4]
unique_numbers = set(numbers)
print(unique_numbers) # {1, 2, 3, 4}
# Empty set (note: {} is an empty dict, not a set)
empty_set = set()Sets are perfect for:
# Automatically removes duplicates
votes = ["Alice", "Bob", "Alice", "Carol", "Bob", "Alice"]
unique_voters = set(votes)
print(unique_voters) # {'Bob', 'Alice', 'Carol'}
print(len(unique_voters)) # 3# Track unique visitors throughout the day
visitors = {"alice", "bob", "carol", "alice", "bob", "david"}
# Convert list to set for uniqueness
visitor_list = ["alice", "bob", "carol", "alice", "bob", "david"]
unique_visitors = set(visitor_list)
print(f"Total visits: {len(visitor_list)}") # 6
print(f"Unique visitors: {len(unique_visitors)}") # 4
print(f"Who visited: {unique_visitors}")| Method | Purpose | Example |
|---|---|---|
| `add(x)` | Add an item | `colors.add("yellow")` |
| `remove(x)` | Remove an item | `colors.remove("red")` |
| `in` | Check membership | `"red" in colors` |
| `len()` | Count items | `len(colors)` |
| `clear()` | Remove all | `colors.clear()` |
Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep β’ Build Real β’ Verify Skills β’ Launch Forward