Lecture
Intersection, Union, Difference Operations
Set is highly useful when performing set operations such as intersection, union, and difference, which you might have learned in math class.
These set operations are widely used in data analysis, algorithm design, logic implementation, and various other fields.
Intersection
An intersection is a set that contains elements common to both sets.
You can find the intersection using the intersection() method or the & operator.
Set Intersection Operation
set_a = {1, 2, 3} set_b = {3, 4, 5} intersection = set_a & set_b # or set_a.intersection(set_b) print("intersection:", intersection) # Output: {3}
Union
A union is a set that contains all elements from both sets.
Use the union() method or the | operator.
Set Union Operation
set_a = {1, 2, 3} set_b = {3, 4, 5} union = set_a | set_b # or set_a.union(set_b) print("union:", union) # Output: {1, 2, 3, 4, 5}
Difference
A difference is a set containing elements that are in the first set but not in the second set.
You can find the difference using the difference() method or the - operator.
Set Difference Operation
set_a = {1, 2, 3} set_b = {3, 4, 5} difference = set_a - set_b # or set_a.difference(set_b) print("difference:", difference) # Output: {1, 2}
Quiz
0 / 1
Which of the following is the most appropriate word to fill in the blank?
In Python, the intersection of two sets can be found using the method or the & operator.
intersection()
union()
difference()
symmetric_difference()
Lecture
AI Tutor
Help
Code Editor
Run
Generate
Execution Result