Performing Set Operations in Python
Sets are an essential data structure in Python that allow you to store unique elements. They are particularly useful for performing mathematical set operations such as union, intersection, difference, and symmetric difference. In this lesson, we'll explore these operations in detail.
What Are Sets?
A set in Python is an unordered collection of unique elements. Duplicates are automatically removed when creating a set. Sets are mutable, meaning you can add or remove elements after creation.
# Creating a set
my_set = {1, 2, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}Basic Set Operations
Python provides built-in methods and operators to perform various set operations:
1. Union
The union operation combines all unique elements from two sets. It can be performed using the | operator or the .union() method.
set_a = {1, 2, 3}
set_b = {3, 4, 5}
union_set = set_a | set_b
print(union_set) # Output: {1, 2, 3, 4, 5}2. Intersection
The intersection operation returns elements that are common to both sets. Use the & operator or the .intersection() method.
intersection_set = set_a & set_b
print(intersection_set) # Output: {3}3. Difference
The difference operation returns elements present in the first set but not in the second. You can use the - operator or the .difference() method.
difference_set = set_a - set_b
print(difference_set) # Output: {1, 2}4. Symmetric Difference
The symmetric difference includes elements that are in either of the sets but not in their intersection. Use the ^ operator or the .symmetric_difference() method.
symmetric_diff = set_a ^ set_b
print(symmetric_diff) # Output: {1, 2, 4, 5}Practical Applications
Set operations are widely used in real-world programming scenarios, such as:
- Finding unique items in a dataset.
- Filtering out duplicates while merging datasets.
- Comparing two groups of items efficiently.
Understanding these operations will enhance your ability to manipulate collections effectively in Python.