Hash sets in practice
After this: Use set, frozenset and HashSet, and know what they do and do not promise about order.
On this page · 5 sections · 3 checks
You now know what a set does, what is inside it, and the two main ways to use it: combining sets and spotting repeats. This lesson collects what Python and Java give you, and the rules that catch people out.
The basic calls
s = {"cat", "act"} # a set literals = set(["cat", "act"]) # from a list; set() is empty, {} is an empty dicts.add("dog") # add: no value to gives.discard("emu") # remove if present; s.remove("emu") would raise KeyErrorprint("act" in s, len(s)) # membership and sizeprint(sorted(s)) # the order is not promised: sort before you printTrue 3 ['act', 'cat', 'dog']
Set<String> s = new HashSet<>(Set.of("cat", "act")); // Set.of cannot change; copy it so it can grows.add("dog"); // add: no value to give; true if it was news.remove("emu"); // false if missing, no exceptionSystem.out.println(s.contains("act") + " " + s.size()); // membership and sizeSystem.out.println(new TreeSet<>(s)); // the order is not promised: sort before you printtrue 3 [act, cat, dog]
Most of this you have seen already. Two things are new.
- There is a safe way to remove an item that may not be there. In Python, s.discard("emu") does nothing if emu is missing, while s.remove("emu") raises a KeyError.In Java, s.remove("emu") returns false if emu is missing, and raises no error.
- The items are sorted before printing, for a reason the next section explains.
Here is every common operation with its cost. As before, n and m are the sizes of the two sets.
| Operation | Python set | Java HashSet | Cost |
|---|---|---|---|
| Add | s.add(x) | s.add(x) | O(1) on average |
| Membership test | x in s | s.contains(x) | O(1) on average |
| Remove | s.discard(x), s.remove(x) | s.remove(x) | O(1) on average |
| Size | len(s) | s.size() | O(1) |
| Union | a | b | copy, then addAll(b) | O(n + m) on average |
| Intersection | a & b | copy, then retainAll(b) | O(n + m) at most, on average |
| Difference | a - b | copy, then removeAll(b) | O(n + m) at most, on average |
| Go through every item | for x in s | for (x : s) | O(n), plus any empty slots, in no promised order |
"On average" has the same conditions as for a hash map: the hash function must spread the keys, and the table must grow before it gets crowded.
An add sometimes costs more, because the table is full enough to need growing, and every key must move. This happens rarely, so the cost per add stays small when you average it over many adds. The word for this kind of average is .
Order is not promised
A set does not remember the order in which you added items. If you loop over a set, the items can come out in any order.
s = set("hello")print(len(s)) # 4 different letters, in whatever orderprint(sorted(s)) # sort when you need an order you can rely on4 ['e', 'h', 'l', 'o']
Set<Character> s = new HashSet<>();for (char ch : "hello".toCharArray()) s.add(ch);System.out.println(s.size()); // 4 different letters, in whatever orderSystem.out.println(new TreeSet<>(s)); // sort when you need an order you can rely on4 [e, h, l, o]
The word hello has five letters but four different ones, so the set holds four. Sorting gives an order that you can rely on.
A set as a key
Sometimes you want a set to be a key in a map, or a member of another set. For example, you may want to treat cat and act as one pair, in whichever order they were written.
There is a problem. A key must never change its hash, or the table looks for it in the wrong slot (the lesson Update, delete and what can be a key explains why). A set can change, so its hash could change. For this reason Python does not allow a plain set as a key.
Python has frozenset for this job. A frozenset is a set that cannot change after it is created. Two frozensets with the same members are equal, in whatever order the members were listed. In the Python version below, the last statement fails on purpose, to show the error.
pairs = {}pairs[frozenset(["cat", "act"])] = "anagrams" # a set as a key must be frozenprint(pairs[frozenset(["act", "cat"])]) # same members, same key, whatever the orderpairs[{"cat", "act"}] = "anagrams"# TypeError: ... unhashable type: 'set'Map<Set<String>, String> pairs = new HashMap<>();pairs.put(Set.of("cat", "act"), "anagrams"); // Set.of cannot change: a safe keySystem.out.println(pairs.get(Set.of("act", "cat"))); // same members, same key, whatever the orderCheck yourself
Which of these jobs needs a set more than a list?
You add the letters of hello to a set, then loop over it and print each letter. What can you rely on?
What does this print?
seen = set()seen.add(frozenset([1, 2]))seen.add(frozenset([2, 1]))seen.add(frozenset([1, 2, 3]))print(len(seen))Set<Set<Integer>> seen = new HashSet<>();seen.add(Set.of(1, 2));seen.add(Set.of(2, 1));seen.add(Set.of(1, 2, 3));System.out.println(seen.size());Connect
- Use set, frozenset and HashSet with their costs in mind.
- Say what Python and Java promise about the order of a set: nothing.
- Say when a set beats a list, and what it gives up.