Skip to content

Mojo Sets

A set is a group of values where each value appears at most once. You use one when you care about “is this in the group?” and not about order or position: tags on a post, words you’ve already seen, users who liked something. Mojo’s set type is Set, and it works much like Python’s set, including the |, & and - operators.

Write the values in curly braces, without colons (with colons it would be a dictionary):

def main():
var colors = {"red", "green", "blue", "red"}
print(colors)
print(len(colors))

Output:

{red, green, blue}
3

"red" was written twice, but the set keeps it once. That’s the whole point of a set: duplicates disappear on their own.

To make an empty set, or to name the type yourself, you write Set[String](). Unlike List and Dict, the name Set isn’t available everywhere. You have to import it first, and the compiler tells you so if you forget:

def main():
var seen = Set[String]()
print(seen)
sets.mojo:2:16: error: use of unknown declaration 'Set'; did you mean to import it from 'std.collections'? Add 'from std.collections import Set'
var seen = Set[String]()
^~~
mojo: error: failed to parse the provided Mojo source module

Add the import line at the top and it works:

from std.collections import Set
def main():
var seen = Set[String]()
print(seen, len(seen))

Output:

{} 0

You only need the import when you write the name Set. A literal like {"red", "green"} works without it.

def main() raises:
var tags = {"mojo", "python"}
tags.add("tutorial")
tags.add("mojo")
print(tags)
tags.discard("java")
tags.remove("python")
print(tags)
print(len(tags))

Output:

{mojo, python, tutorial}
{mojo, tutorial}
2
  • add(x) puts a value in. Adding something that’s already there does nothing.
  • discard(x) takes a value out if it’s there, and quietly does nothing if it isn’t.
  • remove(x) takes a value out, but raises an error if it isn’t there. That’s why this main is marked raises.

Use discard unless a missing value really means something went wrong. There’s also clear() to empty the set and pop() to take out one value.

in is what sets are best at. The Set API docs describe membership checks as O(1) on average: roughly the same time whether the set holds ten values or a million. With a list, in has to look at the items one by one.

def main():
var banned = {"spam", "scam", "junk"}
var words: List[String] = ["hello", "spam", "world", "junk"]
for w in words:
if w in banned:
print(w, "is banned")
else:
print(w, "is fine")

Output:

hello is fine
spam is banned
world is fine
junk is banned

A quick way to drop duplicates is to build a set from a list:

from std.collections import Set
def main():
var visits: List[Int] = [7, 3, 7, 1, 3, 7]
var unique = Set[Int](visits)
print(unique)
print(len(unique), "different visitors")

Output:

{7, 3, 1}
3 different visitors

Set[Int](visits) adds every item of the list to a new set.

Sets support the classic set operations, both as operators and as methods with readable names:

def main():
var alice = {"tea", "cake", "soup"}
var bob = {"cake", "soup", "pie"}
print(alice | bob)
print(alice & bob)
print(alice - bob)
print(alice ^ bob)

Output:

{tea, cake, soup, pie}
{cake, soup}
{tea}
{tea, pie}
Operator Method Gives you
a | b a.union(b) Everything in either set
a & b a.intersection(b) Only what’s in both
a - b a.difference(b) What’s in a but not in b
a ^ b a.symmetric_difference(b) What’s in exactly one of them

These all make a new set and leave alice and bob unchanged. If you want to change a set in place, use update() or the |=, &= and -= operators.

You can ask how two sets relate to each other:

def main():
var needed = {"flour", "eggs"}
var pantry = {"flour", "eggs", "milk", "salt"}
print(needed.issubset(pantry))
print(pantry.issuperset(needed))
print(needed <= pantry)
print(needed.isdisjoint({"rice"}))
print({"eggs", "flour"} == needed)

Output:

True
True
True
True
True
  • a.issubset(b) (or a <= b): every value in a is also in b.
  • a.issuperset(b) (or a >= b): a contains everything in b.
  • a.isdisjoint(b): they have nothing in common.
  • a == b: same values. Order doesn’t matter, which is why the last line is True.

A for loop works on a set like on any other collection:

def main():
var langs = {"mojo", "rust", "zig"}
for lang in langs:
print(lang.upper())

Output:

MOJO
RUST
ZIG

In this version of Mojo, sets happen to give values back in the order you added them. But the Mojo manual describes Set as “an unordered collection”, and nothing promises an order. If you need a fixed order, copy the values into a List and sort it (see Mojo Sorting & Searching).

Set values have the same rules as dictionary keys: Mojo must be able to hash and compare them. Int, String, Bool and tuples of those are fine. The Mojo manual’s Types page calls this the KeyElement requirement. Sets are useful for tracking positions on a grid:

from std.collections import Set
def main():
var visited = Set[Tuple[Int, Int]]()
visited.add((0, 0))
visited.add((0, 1))
visited.add((0, 0))
print(len(visited))
print((0, 1) in visited)

Output:

2
True
Python Mojo
Make one s = {1, 2} var s = {1, 2}
Empty set set() Set[Int]() after from std.collections import Set
From a list set(xs) Set[Int](xs)
Operators |, &, -, ^ Same
remove on a missing value KeyError Raises an error too
Mixed types {1, "a"} is fine All values have one type

Ada likes "chess", "hiking" and "jazz". Bo likes "jazz", "chess" and "cooking". Print what they both like, and what only Ada likes.

Hint: that’s & and -.

Show solution
def main():
var ada = {"chess", "hiking", "jazz"}
var bo = {"jazz", "chess", "cooking"}
print("both:", ada & bo)
print("only Ada:", ada - bo)

Output:

both: {chess, jazz}
only Ada: {hiking}

& keeps values found in both sets. - keeps values from the left set that aren’t in the right one.

Go through the list [4, 8, 15, 8, 4] and print the first number you see for the second time (that’s 8).

Hint: keep a Set[Int] of numbers you’ve already seen. Before adding a number, check if it’s in the set.

Show solution
from std.collections import Set
def main():
var nums: List[Int] = [4, 8, 15, 8, 4]
var seen = Set[Int]()
for n in nums:
if n in seen:
print("first repeat:", n)
break
seen.add(n)

Output:

first repeat: 8

break stops the loop as soon as we find the answer, so the second 4 is never checked.

  • A set holds unique values: var s = {"a", "b"}. Duplicates are dropped.
  • To write the type name, import it: from std.collections import Set, then Set[Int]().
  • add puts a value in, discard takes it out safely, remove raises if it’s missing.
  • x in s is fast, even for big sets. Set[Int](my_list) removes duplicates from a list.
  • Combine with | (union), & (intersection), - (difference), ^ (symmetric difference).
  • Compare with issubset, issuperset, isdisjoint and ==. Don’t rely on a set’s order.

Next up: tuples, small fixed groups of values that can have different types.

Quick check

1. What does print({"a", "b", "a"}) show?
2. You want an empty set of strings. Which code works?
3. Which method removes a value without raising an error if the value is missing?
4. What is {1, 2, 3} & {2, 3, 4}?