4.3 Sets
Learning about sets for storing unique items and performing mathematical operations like union, intersection, and difference, taking advantage of their speed in membership testing.
Sets are unordered and mutable collections of unique items. This means a set cannot contain duplicate items. If you try to add a duplicate, it is simply ignored.
Key features of sets:
- Unordered: Items do not have a specific order or index. You cannot access items with `my_set[0]`.
- Mutable: You can add or remove items.
- Do Not Allow Duplicates: This is their main feature.
Sets are declared using curly braces `{}`, but an empty set is created with the `set()` function. If you use `{}`, you will create an empty dictionary.
Creating a Set
# Creating sets
# Set of numbers (duplicates are ignored)
numbers_set = {1, 2, 3, 4, 5, 1, 2, 6}
print(f"Set of numbers: {numbers_set}")
# Creating an empty set
empty_set = set()
print(f"Empty set: {empty_set}, Type: {type(empty_set)}")
# Creating a set from a list (removes duplicates)
list_to_set = set([1, 2, 2, 3, 4, 4])
print(f"List to set: {list_to_set}")
Basic Operations and Mathematical Operations
The power of sets lies in their ability to perform mathematical set operations very efficiently.
# Set operations
set_A = {1, 2, 3, 4}
set_B = {3, 4, 5, 6}
# Adding an item
set_A.add(5)
print(f"set_A after add(5): {set_A}")
# Removing an item
set_A.discard(10) # Does not raise an error if the item does not exist
set_A.remove(1) # Raises a KeyError if the item does not exist
print(f"set_A after removal: {set_A}")
# Union: All items from both sets
union_set = set_A.union(set_B) # or set_A | set_B
print(f"Union: {union_set}")
# Intersection: Only common items
intersection_set = set_A.intersection(set_B) # or set_A & set_B
print(f"Intersection: {intersection_set}")
# Difference: Items that exist in A but not in B
difference_set = set_A.difference(set_B) # or set_A - set_B
print(f"Difference (A - B): {difference_set}")
# Symmetric Difference: Items that exist in one of the two, but not in both
symmetric_diff_set = set_A.symmetric_difference(set_B) # or set_A ^ set_B
print(f"Symmetric Difference: {symmetric_diff_set}")
Tip!
When to use a Set?
- Removing Duplicates: The fastest way to get the unique items from a list.
- Membership Testing: The check `if item in my_set:` is extremely fast, much faster than in a list, especially for large collections.
- Mathematical Operations: When you need to find common items, differences, or the union of two collections.
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.