Sets in Python
Overview
This lesson covers sets in Python, a collection type that is unordered, mutable, and optimized for quickly checking whether an item is present. Sets are ideal for storing unique items and performing common mathematical set operations.
Introduction
Sets are collections of unique elements. They are defined in Python using curly braces {}
or the set()
constructor. Unlike lists or tuples, sets do not allow duplicate elements, making them useful for operations involving uniqueness.
Creating a Set
- Using Curly Braces:
colors = {'red', 'green', 'blue'}
- Using the
set()
Constructor:
numbers = set([1, 2, 3, 2])
In the second example, numbers will be {1, 2, 3} because sets automatically remove duplicate entries.
Accessing Set Elements
Sets do not support indexing, slicing, or other sequence-like behavior since they are unordered. The only way to access elements in a set is by iterating over the set or checking for a specific element.
Basic Set Operations
- Adding Elements: Use the .add() method to add a single element or .update() to add multiple elements.
colors.add('yellow')
colors.update(['orange', 'purple'])
- Removing Elements: Use the
.remove()
or.discard()
methods..remove()
raises an error if the element is not present, while.discard()
does not.
colors.remove('red') # Raises KeyError if 'red' is not in the set
colors.discard('red') # Does nothing if 'red' is not in the set
- Checking Membership: Use the in keyword.
if 'green' in colors:
print("Green is in the set")
Set Operations
Python sets support mathematical set operations like union, intersection, difference, and symmetric difference.
-
Union: Combines elements from two sets without duplicates. Use the operator or .union()
method.
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # Output: {1, 2, 3, 4, 5}
- Intersection: Finds elements present in both sets. Use the & operator or
.intersection()
method.
print(a & b) # Output: {3}
- Difference: Finds elements in the first set but not in the second. Use the - operator or .difference() method.
print(a - b) # Output: {1, 2}
- Symmetric Difference: Finds elements in either set but not in both. Use the ^ operator or .symmetric_difference() method.
print(a ^ b) # Output: {1, 2, 4, 5}
Immutable Sets
Python also offers frozenset, an immutable version of set. You cannot add or remove elements from a frozenset.
immutable_colors = frozenset(['red', 'green', 'blue'])
Conclusion
Sets in Python provide a powerful and flexible way to work with collections of unique items. They are particularly useful for performing mathematical set operations and for cases where you need to ensure elements are unique.