Mojo Sets

A set stores unique values with no duplicates and no guaranteed order. When you add the same item twice, the set keeps only one copy. Sets are powerful for membership testing, deduplication, and mathematical operations like union and intersection.

The Attendance Register Analogy

  Students who entered the classroom (a set):

  Raw log (with repeats):     Set result (unique only):
  Alice enters  →             ┌──────────────────────┐
  Bob enters    →             │  Alice               │
  Alice enters  → DUPLICATE   │  Bob                 │
  Carol enters  →             │  Carol               │
  Bob enters    → DUPLICATE   │  David               │
  David enters  →             └──────────────────────┘
                              4 unique people, not 6 entries

Creating a Set

from collections import Set

fn main():
    var tags = Set[String]("python", "mojo", "ai", "python")
    print(len(tags))   # 3 — "python" appears once

Adding and Removing Elements

from collections import Set

fn main():
    var colors = Set[String]()
    colors.add("red")
    colors.add("green")
    colors.add("blue")
    colors.add("red")     # ignored — already present

    print(len(colors))    # 3

    colors.discard("green")
    print(len(colors))    # 2

The discard() method removes an element if it exists and does nothing if it does not. The remove() method raises an error if the element is missing — use discard() when you are not sure.

Membership Testing

Checking whether a value exists in a set is very fast, even for large sets — faster than scanning a list.

from collections import Set

fn main():
    var allowed_users = Set[String]("admin", "editor", "viewer")

    var user = "editor"
    if user in allowed_users:
        print(user, "has access")     # editor has access
    else:
        print(user, "is not allowed")
Membership check speed:
  List [A, B, C, ..., Z]:  Check each item → up to N comparisons
  Set  {A, B, C, ..., Z}:  Hash lookup     → ~1 step regardless of size

Set Operations

Sets support the same mathematical operations you learned in school: union, intersection, and difference.

Union — All Items from Both Sets

  Set A:  {1, 2, 3, 4}
  Set B:  {3, 4, 5, 6}
  ─────────────────────
  A | B:  {1, 2, 3, 4, 5, 6}

  (everything from A and everything from B, no duplicates)

Intersection — Items Present in Both Sets

  Set A:  {1, 2, 3, 4}
  Set B:  {3, 4, 5, 6}
  ─────────────────────
  A & B:  {3, 4}

  (only items that appear in BOTH A and B)

Difference — Items in A but not in B

  Set A:  {1, 2, 3, 4}
  Set B:  {3, 4, 5, 6}
  ─────────────────────
  A - B:  {1, 2}

  (items from A that B does not have)

Symmetric Difference — Items in One but not Both

  Set A:  {1, 2, 3, 4}
  Set B:  {3, 4, 5, 6}
  ─────────────────────
  A ^ B:  {1, 2, 5, 6}

  (items that appear in exactly one of the two sets)

Code Example

from collections import Set

fn main():
    var morning_readers = Set[String]("Alice", "Bob", "Carol")
    var evening_readers = Set[String]("Bob", "Carol", "David")

    # Who reads at all? (union)
    var all_readers = morning_readers | evening_readers
    print(len(all_readers))   # 4

    # Who reads both morning and evening? (intersection)
    var both = morning_readers & evening_readers
    # both contains "Bob" and "Carol"
    print(len(both))          # 2

    # Who reads only in the morning? (difference)
    var morning_only = morning_readers - evening_readers
    # morning_only contains "Alice"
    print(len(morning_only))  # 1

Subset and Superset Checks

from collections import Set

fn main():
    var basics = Set[String]("html", "css")
    var full_stack = Set[String]("html", "css", "js", "python")

    print(basics <= full_stack)   # True — basics is a subset of full_stack
    print(full_stack >= basics)   # True — full_stack is a superset of basics
Subset diagram:

  full_stack: { html, css, js, python }
                  ↑     ↑
  basics:       { html, css }
  basics is entirely inside full_stack → subset relationship

Deduplication Use Case

The most common practical use of a set is removing duplicates from a list.

from collections import Set, List

fn main():
    var raw_tags = List[String]("ai", "mojo", "ai", "python", "mojo", "mojo")

    var unique_tags = Set[String]()
    for i in range(len(raw_tags)):
        unique_tags.add(raw_tags[i])

    print(len(raw_tags))     # 6 — original with duplicates
    print(len(unique_tags))  # 3 — unique only

Set vs List vs Dict

Feature              | Set      | List     | Dict
---------------------|----------|----------|--------
Ordered              | No       | Yes      | No
Allows duplicates    | No       | Yes      | Keys: No
Key-value pairs      | No       | No       | Yes
Fast membership test | Yes      | No       | Yes (keys)
Use when             | Unique   | Ordered  | Key→Value
                     | items    | data     | lookups

Key Takeaways

A set stores unique values only — duplicates are silently ignored when added. Use add() to insert and discard() to remove elements safely. Membership testing with in is extremely fast. Set operations — union (|), intersection (&), difference (-), and symmetric difference (^) — mirror mathematical set theory. Sets are the right tool when uniqueness matters more than order.

Leave a Comment

Your email address will not be published. Required fields are marked *