AnyCompiler

Sets

A set is an unordered collection with one defining rule: every value in it is unique. Add a duplicate and nothing happens — it's already there.

numbers = {1, 2, 3, 2, 1}
print(numbers)

numbers.add(4)
print(numbers)

a = {1, 2, 3}
b = {2, 3, 4}
print(a | b)
print(a & b)
print(a - b)
Output
{1, 2, 3}
{1, 2, 3, 4}
{1, 2, 3, 4}
{2, 3}
{1}
  • {1, 2, 3, 2, 1} collapses down to {1, 2, 3} the moment it's created — duplicates just don't survive
  • | is union — everything in either set
  • & is intersection — only what's in both
  • - is difference — what's in the first set but not the second

These are genuinely useful, not just a novelty: deduplicating a list is as simple as list(set(my_list)), and checking whether two collections overlap is a single & away.

Next: conditional statements — making your code actually branch based on a value.

Practice exercise

Create a = {1, 2, 3} and b = {2, 3, 4}. Print their intersection using a & b.