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.
Making a set
Section titled “Making a set”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 moduleAdd 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:
{} 0You only need the import when you write the name Set. A literal like {"red", "green"} works without it.
Adding and removing
Section titled “Adding and removing”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}2add(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 thismainis markedraises.
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.
Checking membership
Section titled “Checking membership”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 finespam is bannedworld is finejunk is bannedRemoving duplicates from a list
Section titled “Removing duplicates from a list”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 visitorsSet[Int](visits) adds every item of the list to a new set.
Combining sets
Section titled “Combining sets”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.
Comparing sets
Section titled “Comparing sets”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:
TrueTrueTrueTrueTruea.issubset(b)(ora <= b): every value inais also inb.a.issuperset(b)(ora >= b):acontains everything inb.a.isdisjoint(b): they have nothing in common.a == b: same values. Order doesn’t matter, which is why the last line isTrue.
Looping over a set
Section titled “Looping over a set”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:
MOJORUSTZIGIn 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).
What can go in a set?
Section titled “What can go in a set?”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:
2TrueComing from Python?
Section titled “Coming from Python?”| 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 |
Practice
Section titled “Practice”1. Shared interests
Section titled “1. Shared interests”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.
2. First repeat
Section titled “2. First repeat”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: 8break 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, thenSet[Int](). addputs a value in,discardtakes it out safely,removeraises if it’s missing.x in sis 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,isdisjointand==. Don’t rely on a set’s order.
Next up: tuples, small fixed groups of values that can have different types.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Set API docs: every set method and operator.
- Mojo manual: Types: the official introduction to
Setand the other collections. - collections module: the other collection types in the standard library, such as
DequeandCounter.