Sets in Python are unordered collections of unique elements. This means that duplicate values are automatically eliminated, and the order in which you add elements doesn’t affect how they’re stored or retrieved. Sets are mutable (changeable) by default, unless you use the frozenset
type, which is immutable.
Sets are particularly useful for tasks that require efficient membership testing (checking if an element exists), removing duplicates from a list, and performing set operations such as union, intersection, and difference.
Table of Contents
- Creating Sets
- Adding and Updating Elements
- Removing Elements
- Set Operations
- Set Methods
- Other Set Operations
- Built-in Functions with Sets
- Frozensets
1. Creating Sets
You can create sets using curly braces {}
or the set()
constructor. Note that an empty set must be created using set()
; {}
creates an empty dictionary.
# Using curly braces
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
# Using the set() constructor
another_set = set([6, 7, 8, 8]) # Duplicates are automatically removed
print(another_set) # Output: {8, 6, 7}
empty_set = set()
print(empty_set) # Output: set()
Remember that sets are unordered, so the output order might differ from the input order.
2. Adding and Updating Elements
Use the add()
method to add a single element and the update()
method to add multiple elements.
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
my_set.update([5, 6, 7])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
my_set.update({8, 9}, (10,)) # Update with set and tuple
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
3. Removing Elements
Several methods allow for element removal. remove()
raises a KeyError
if the element isn’t found, while discard()
does not.
my_set = {1, 2, 3, 4, 5}
my_set.remove(3) # Raises KeyError if element not found
print(my_set) # Output: {1, 2, 4, 5}
my_set.discard(6) # Does not raise an error if element not found
print(my_set) # Output: {1, 2, 4, 5}
removed_element = my_set.pop() # Removes and returns an arbitrary element
print(removed_element) # Output: (a random element)
print(my_set)
my_set.clear() # Removes all elements
print(my_set) # Output: set()
4. Set Operations
Sets support standard mathematical set operations:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union: combines elements from both sets
union_set = set1 | set2 # or set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
# Intersection: elements present in both sets
intersection_set = set1 & set2 # or set1.intersection(set2)
print(intersection_set) # Output: {3}
# Difference: elements in set1 but not in set2
difference_set = set1 - set2 # or set1.difference(set2)
print(difference_set) # Output: {1, 2}
# Symmetric Difference: elements in either set1 or set2, but not both
symmetric_difference_set = set1 ^ set2 # or set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}
5. Set Methods
Python offers many built-in methods for set manipulation:
my_set = {1, 2, 3, 4, 5}
print(my_set.issubset({1, 2, 3, 4, 5, 6})) # True
print(my_set.issuperset({1, 2})) # True
print(my_set.isdisjoint({6, 7, 8})) # True - no common elements
print(my_set.copy()) # creates a shallow copy of the set
6. Other Set Operations
Beyond the basic operations, you can check for membership, find the length, and more:
my_set = {1, 2, 3}
print(1 in my_set) # Output: True
print(4 not in my_set) # Output: True
print(len(my_set)) # Output: 3
7. Built-in Functions with Sets
Functions like all()
, any()
, sum()
, min()
, max()
work with sets:
my_set = {1, 2, 3, 4, 5}
print(sum(my_set)) # Output: 15
print(min(my_set)) # Output: 1
print(max(my_set)) # Output: 5
print(all(x > 0 for x in my_set)) # Output: True
print(any(x == 0 for x in my_set)) # Output: False
8. Frozensets
frozenset
creates an immutable set. Once created, you can’t add or remove elements. They’re useful as dictionary keys or elements of other sets.
my_frozenset = frozenset({1, 2, 3})
# my_frozenset.add(4) # This will raise an AttributeError
print(my_frozenset) # Output: frozenset({1, 2, 3})