Sets
Introduction to Sets
Sets are unordered collections of unique elements. Unlike lists, sets don't allow duplicate values and don't maintain order. Sets are perfect for membership testing, removing duplicates, and mathematical set operations.
Sets are mutable (you can add/remove items), but the items themselves must be immutable (like strings, numbers, or tuples).
Creating Sets
Sets are created using curly braces {} or the set() function:
Set Operations
Sets support mathematical set operations:
Set Methods
Common methods for working with sets:
When to Use Sets
✅ Use Sets When:
• You need unique values (no duplicates)
• Fast membership testing is important
• You need set operations (union, intersection, etc.)
• Order doesn't matter
💡 Important Notes
• Sets are unordered (order may vary)
• Sets cannot contain mutable items (like lists)
• Sets are faster than lists for membership testing