Sets

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.

Python
Output

What will be the output?

Python

The & operator returns only elements found in both sets.

Python
Output

What will be the output?

Python

The - operator returns elements in the first set that are not in the second.

Python
Output

What will be the output?

Python

The ^ operator returns elements that are in one set or the other, but not both.

Python
Output

What will be the output?

Python

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:

Python

Every required ingredient is in the pantry. So required is a subset of pantry.

Python
Output

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python

What will be the output?

Python