Python - Sets
What are Sets?
A set in Python is an unordered collection of unique elements. Sets are mutable but only immutable (hashable) elements can be stored in a set.
Why Use Sets?
- To remove duplicate values from a collection.
- To perform mathematical set operations like union, intersection, difference, etc.
- To test for membership efficiently.
How to Create Sets
python
# Creating sets empty_set = set() fruits = {'apple', 'banana', 'cherry'}
Adding and Removing Items
python
fruits.add('orange') # Adds an item fruits.remove('banana') # Removes an item (raises error if not found) fruits.discard('apple') # Removes if present, no error if absent
Set Operations
python
a = {1, 2, 3} b = {3, 4, 5} print(a | b) # Union: {1, 2, 3, 4, 5} print(a & b) # Intersection: {3} print(a - b) # Difference: {1, 2} print(a ^ b) # Symmetric Difference: {1, 2, 4, 5}
Set Methods
add(),remove(),discard(),clear()union(),intersection(),difference(),issubset(),issuperset()
When to Use Sets?
- To maintain a collection of unique values.
- To perform fast membership testing.
- When order of elements is not important.
Pros
- Automatic handling of duplicates.
- Fast membership tests and set operations.
Cons
- Unordered — no indexing or slicing.
- Cannot store mutable items like lists or dicts.