1. What is a Set?
A set is an unordered collection data type that is iterable, mutable, and contains no duplicate elements. Python sets are based on the mathematical concept of sets.
Key characteristics of a Python set:
- Unordered
- Mutable (except frozen sets)
- Does not allow duplicates
- Supports mathematical operations
2. Creating Sets
Sets are created using curly braces {}
or the built-in set()
function.
Example:
# Creating a set using curly braces
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}
# Creating a set from a list
my_list = [1, 2, 2, 3, 4, 4]
unique_set = set(my_list)
print(unique_set) # Output: {1, 2, 3, 4}
# Creating an empty set
empty_set = set()
print(type(empty_set)) # Output: <class 'set'>
Note:
{}
creates an empty dictionary, not an empty set. Always useset()
to create an empty set.
3. Set Operations
Python supports several useful set operations that mimic mathematical sets:
Union (|
or .union()
)
Combines all elements from two sets, removing duplicates.
A = {1, 2, 3}
B = {3, 4, 5}
# Using operator |
print(A | B) # {1, 2, 3, 4, 5}
# Using .union()
print(A.union(B)) # {1, 2, 3, 4, 5}
Intersection (&
or .intersection()
)
Returns elements common to both sets.
# Using operator &
print(A & B) # {3}
# Using .intersection()
print(A.intersection(B)) # {3}
Difference (-
or .difference()
)
Returns elements present in the first set but not in the second.
# Using operator -
print(A - B) # {1, 2}
# Using .difference()
print(A.difference(B)) # {1, 2}
Symmetric Difference (^
or .symmetric_difference()
)
Returns elements in either set but not in both.
# Using operator ^
print(A ^ B) # {1, 2, 4, 5}
# Using .symmetric_difference()
print(A.symmetric_difference(B)) # {1, 2, 4, 5}
4. Modifying Sets
Sets are mutable, allowing you to add or remove elements.
Adding Elements (.add()
)
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # {1, 2, 3, 4}
Removing Elements (.remove()
and .discard()
)
.remove(element)
removes the element if it exists, raises an error otherwise..discard(element)
removes the element if it exists, does nothing otherwise.
my_set.remove(2)
print(my_set) # {1, 3, 4}
my_set.discard(5) # No error even if element doesn't exist
Pop Elements (.pop()
)
Removes and returns an arbitrary element from the set.
element = my_set.pop()
print(element)
print(my_set)
Clearing Sets (.clear()
)
Empties the set entirely.
my_set.clear()
print(my_set) # set()
5. Set Methods Summary
Method | Description |
---|---|
.add(elem) | Adds an element to the set |
.update(iterable) | Adds multiple elements to the set |
.remove(elem) | Removes element, raises an error if absent |
.discard(elem) | Removes element if it exists |
.pop() | Removes and returns arbitrary element |
.clear() | Removes all elements from the set |
.union(other_set) | Returns union of two sets |
.intersection(other_set) | Returns intersection of two sets |
.difference(other_set) | Returns difference of two sets |
.symmetric_difference(other_set) | Elements not in both sets |
.issubset(other_set) | Checks if the set is a subset |
.issuperset(other_set) | Checks if the set is a superset |
6. Frozen Sets
A frozenset
is an immutable version of a set. Once created, its elements cannot be changed. Frozen sets are useful for using sets as keys in dictionaries or elements of other sets.
Example:
my_frozen_set = frozenset([1, 2, 3])
print(my_frozen_set) # frozenset({1, 2, 3})
# my_frozen_set.add(4) # Raises AttributeError: 'frozenset' object has no attribute 'add'
7. Set Comprehensions
Python supports set comprehensions for concise set creation.
squares = {x * x for x in range(1, 6)}
print(squares) # {1, 4, 9, 16, 25}
8. Practical Examples with Sets
Eliminate duplicates from a list:
duplicates = [1, 2, 3, 2, 1, 5, 5]
unique_items = list(set(duplicates))
print(unique_items) # [1, 2, 3, 5]
Check membership quickly:
my_set = {1, 2, 3, 4}
print(2 in my_set) # True
print(5 in my_set) # False
Summary and Best Practices
-Use sets to store unique, unordered collections of items.
-Remember, sets do not allow indexing or slicing due to their unordered nature.
-Frozen sets are useful as dictionary keys or set elements.
-Set operations (union
, intersection
, etc.) are fast and convenient for comparisons.