5. Set operations

Set operations combine two sets and return a new set without changing the originals.

  • a | b — union: elements that appear in a or b (or both).
  • a & b — intersection: elements that appear in both.
  • a - b — difference: elements in a but not in b.
  • a ^ b — symmetric difference: elements in exactly one of the two sets.

The printed order of a set is not guaranteed, so sorted() is used here to get a stable result.

The same operations are also methods: a.union(b), a.intersection(b), a.difference(b) and a.symmetric_difference(b). Methods accept any iterable, while the operators require both sides to be sets.

set.issubset(other) returns True when every element of the set is also in other:

Coming from JavaScript? Set algebra uses operators: a | b, a & b, a - b, a ^ b. JS Set uses methods such as union() and intersection().

#01

Union

The union a | b contains every element that appears in a or b, without duplicates. Create a = {1, 2, 3} and b = {3, 4}, then print the union in ascending order with sorted(a | b).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Intersection

The intersection a & b contains only the elements present in both sets. With a = {1, 2, 3} and b = {3, 4}, print sorted(a & b).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Difference

The difference a - b contains the elements of a that are not in b. With a = {1, 2, 3} and b = {3, 4}, print sorted(a - b).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Symmetric difference

The symmetric difference a ^ b contains the elements that are in exactly one of the two sets. With a = {1, 2, 3} and b = {3, 4}, print sorted(a ^ b).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#05

Use a set method

a.union(other) does the same as a | other but accepts any iterable. Create a = {1, 2, 3} and print sorted(a.union([3, 4, 5])).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#06

Check a subset

set.issubset(other) returns True when every element of the set is also in other. Create small = {1, 2} and large = {1, 2, 3}, then print small.issubset(large) and large.issubset(small).

Print exactly:

Create a free account to save your progress and unlock chapter 2.