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 containing elements that are common to both sets.
You can find the intersection using the intersection()
method or the &
operator.
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 containing all elements from both sets.
Use the union()
method or the |
operator.
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_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}
What is the appropriate word to fill in the blank?
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result