Set Operations in Python
Sets borrow from mathematics. This lesson introduces union (|), intersection (&), difference (-), symmetric difference (^), and subset checks. These operations let you compare and combine datasets in a single expression.
Sets in Python support mathematical operations. You can combine, compare, and find differences between sets using operators.
The | operator returns a new set with all elements from both sets. Duplicates appear only once.
What will be the output?
The & operator returns only elements found in both sets.
What will be the output?
The - operator returns elements in the first set that are not in the second.
What will be the output?
The ^ operator returns elements that are in one set or the other, but not both.
What will be the output?
You can also check if one set is contained inside another. A set A is a subset of B if every element in A also exists in B.
Subset and superset checks:
Every required ingredient is in the pantry. So required is a subset of pantry.
What will be the output?
What will be the output?
What will be the output?
What will be the output?
What will be the output?