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}
Previous lessonSet Data Type that Does Not Allow Duplicate ValuesNext lessonAdding Elements to a Set
Lessons in this chapter Β· Dictionary and Set Data Types for Managing Structured Data
- 1. Managing Structured Data with Dictionaries
- 2. Utilizing Values Within a Dictionary
- 3. Adding and Modifying Elements in a Dictionary
- 4. Removing a Specific Element from a Dictionary
- 5. Multiple-choice quiz
- 6. Handling Dictionary KeyError Exceptions
- 7. Checking Key Existence in a Dictionary
- 8. Safely Checking for Key Existence in a Dictionary
- 9. Multiple-choice quiz
- 10. Set Data Type that Does Not Allow Duplicate Values
- 11. Intersection, Union, Difference Operations
- 12. Adding Elements to a Set
- 13. Removing Elements from a Set
- 14. Utilizing Values within a Set
- 15. Differences Between Shallow and Deep Copy
- 16. Coding Quiz - Safely Extract Values from a Dictionary
- 17. Multiple-choice quiz
- 18. Fill-in-the-blank quiz
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
Design
Upload
Notes
Favorites
Help