IntermediateLesson firstCategory 5 of 20

Sets & Set Operations

Work with unique collections and set algebra. Read the lesson first, then move through the exercises in order.

10 Sections5 Exercises

After reading

Practice Arena

Begin with the first exercise, then continue step by step through the module.

Start with Data Reconciliation

Study Material

Read the full lesson

What a set is

A set is an unordered collection of unique items. It is great for removing duplicates and for fast membership checks.

Creating sets

Use braces for non-empty sets or set() for empty sets.

python
nums = {1, 2, 3} words = set(["a", "b", "a"]) # {'a', 'b'} empty = set() # {} is a dict, not a set

Membership tests are fast

Sets are optimized for membership checks.

python
print("a" in words) # True

Adding and removing items

Use add, remove, or discard.

python
s = {1, 2, 3} s.add(4) s.remove(2) # error if missing s.discard(9) # no error if missing

Set operations

Union, intersection, difference, and symmetric difference are built in.

python
a = {1, 2, 3} b = {3, 4, 5} print(a | b) # union print(a & b) # intersection print(a - b) # difference print(a ^ b) # symmetric difference

Subsets and supersets

You can test relationships with <= and >= or with methods.

python
small = {1, 2} large = {1, 2, 3} print(small <= large) print(large >= small)

When order matters

Sets do not keep order. If you need order, convert to a list and sort it.

python
ordered = sorted(list(a))

Frozen sets (immutable sets)

If you need a set as a dictionary key, use frozenset().

python
f = frozenset([1, 2, 3])

Common mistakes to avoid

  • Using {} for an empty set.
  • Expecting sets to keep order.
  • Putting a list or dict inside a set.

What you should understand after this lesson

  • How to create sets and remove duplicates.
  • How to use union, intersection, difference, and symmetric difference.
  • How to check subset and superset relationships.
  • When to convert a set back to a list.

Interactive

Exercises for this topic

These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.