Python Sets and Set Operations
What is a Set in Python?
A set is an unordered, unindexed, and mutable collection of unique elements. It is defined using curly braces {} or the set() function.
Basic Set Syntax:
my_set = {1, 2, 3, 4}
print(my_set)
Output:
{1, 2, 3, 4}
Duplicates are automatically removed in a set.
Creating a Set
# From a list
set1 = set([1, 2, 3, 3])
print(set1) # {1, 2, 3}
# Using curly braces
set2 = {4, 5, 6}
Accessing Set Items
Sets are unordered, so you cannot access items by index.
for item in set1:
print(item)
Add & Update Items in a Set
Add an element:
set1.add(4)
print(set1)
Update multiple items:
set1.update([5, 6])
print(set1)
Remove Elements from a Set
set1.remove(2) # Removes 2; throws error if not found
set1.discard(10) # Safe remove; no error if not found
set1.pop() # Removes a random element
set1.clear() # Empties the set
Python Set Operations (with Examples)
Let's define two sets for demonstration:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
1. Union (| or .union())
Combines elements from both sets without duplicates.
print(a | b)
print(a.union(b))
Output:
{1, 2, 3, 4, 5, 6}
2. Intersection (& or .intersection())
Gets common elements in both sets.
print(a & b)
print(a.intersection(b))
Output:
{3, 4}
3. Difference (- or .difference())
Elements in a but not in b.
print(a - b)
print(a.difference(b))
Output:
{1, 2}
4. Symmetric Difference (^ or .symmetric_difference())
Elements in either set but not both.
print(a ^ b)
print(a.symmetric_difference(b))
Output:
{1, 2, 5, 6}
5. Set Membership Test
print(3 in a) # True
print(10 not in b) # True
Advanced Set Methods
Method | Description |
---|---|
issubset(other_set) | Returns True if set is subset |
issuperset(other_set) | Returns True if set is superset |
isdisjoint(other_set) | Returns True if sets have no items in common |
Frozen Sets in Python
A frozenset is immutable and hashable.
fs = frozenset([1, 2, 3])
# fs.add(4) Will raise an error