Python Sets
What is a Set?
A set is an unordered collection of unique elements. Sets are mutable, but the items they hold must be immutable (e.g., numbers, strings, tuples).
You can create sets using curly braces `{}` or with the `set()` constructor.
Example
# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 4, 5])
print(fruits)
print(numbers)
Output
{'cherry', 'banana', 'apple'} {1, 2, 3, 4, 5}
Set Characteristics
- Unordered: Elements have no guaranteed order
- Unindexed: Elements cannot be accessed by index or position
- Unique: Duplicate elements are automatically removed
- Mutable: Sets can be updated (add/remove items), but all elements must be immutable types
Basic Set Operations
Sets support common mathematical operations like union, intersection, and difference.
Example
# Set operations
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
print(A | B) # Union → {1, 2, 3, 4, 5, 6}
print(A & B) # Intersection → {3, 4}
print(A - B) # Difference → {1, 2}
print(A ^ B) # Symmetric difference → {1, 2, 5, 6}
Output
{1, 2, 3, 4, 5, 6} {3, 4} {1, 2} {1, 2, 5, 6}
Set Methods
Python provides many built-in methods to work with sets.
Method | Description | Example |
---|---|---|
add() | Add a single element | fruits.add('orange') |
update() | Add multiple elements | fruits.update(['kiwi', 'melon']) |
remove() | Remove an element (KeyError if missing) | fruits.remove('banana') |
discard() | Remove an element (no error if missing) | fruits.discard('pear') |
pop() | Remove and return a random element | fruits.pop() |
clear() | Remove all elements | fruits.clear() |