What a set is
After this: Add to a set, ask whether it holds an item, and say when to use one.
On this page · 6 sections · 3 checks
Imagine you are checking guests at the door of a party. You hold a guest list. Each time someone arrives, you ask one question: is this name on the list?
The answer is yes or no. You do not care which name was written first, or which name is third. A name also needs to be on the list only once. Writing Bea's name a second time does not change who is invited.
Programs ask this kind of question all the time. Is this username already taken? Is this email address blocked? Have I visited this web page before? Each one is the same question: is this item in the group?
A is a collection built for that question. It follows two rules.
- It holds each item once. There are no repeats.
- You can ask it whether it holds an item, and it answers yes or no.
An item in a set is called a of the set, like a member of a club. Asking "is this item in the set?" is called a . You will see this phrase often in this tutorial. It always means that one yes-or-no question.
The smallest example
Let us follow a set of guests one step at a time. It starts empty.
- Add
amir. The set holdsamir. - Add
bea. The set holdsamirandbea. - Add
amiragain. He is already there, so nothing changes. The set still holds two names.
Here are the same three steps in code. In Java, Set and HashSet come from the java.util package.
guests = set() # an empty setguests.add("amir")guests.add("bea")guests.add("amir") # already there: nothing changesprint(len(guests))2
Set<String> guests = new HashSet<>(); // an empty setguests.add("amir");guests.add("bea");guests.add("amir"); // already there: nothing changesSystem.out.println(guests.size());2
- set()new HashSet<>() creates an empty set.
addputs an item in the set.- len(guests)guests.size() tells you how many items the set holds.
The second add of amir did not cause an error, and it did not raise the count. The set noticed the repeat and did nothing.
Asking the set
Now we ask questions. Start again with amir and bea in the set.
- Is
beain the set? Yes. - Is
kaiin the set? No. - Bea cannot come after all, so remove
bea. - Is
beain the set? No, not any more.
guests = set()guests.add("amir")guests.add("bea")print("bea" in guests) # is bea here?print("kai" in guests) # is kai here?guests.remove("bea")print("bea" in guests) # is bea still here?True False False
Set<String> guests = new HashSet<>();guests.add("amir");guests.add("bea");System.out.println(guests.contains("bea")); // is bea here?System.out.println(guests.contains("kai")); // is kai here?guests.remove("bea");System.out.println(guests.contains("bea")); // is bea still here?true false false
The membership test is "bea" in guestsguests.contains("bea"). It gives Truetrue or Falsefalse. The remove call takes an item out of the set.
Why not use a list?
You could keep the names in a list. A set is better for this job for two reasons.
A list keeps repeats. If you add amir to a list twice, the list holds him twice. To stop that, you would have to search the list before every add.
A list is slow to search. To find out whether kai is in a list, the computer looks at the names one at a time, from the start. If kai is not there, it must look at every name. One "no" from a list of a million names takes a million looks. Programmers write this cost as O(n), which means the work grows with the size of the list.
Python's set and Java's HashSet work differently. Both are a , which goes almost straight to the place where a name would be. On average, the number of steps stays small however many names it holds. Programmers write this cost as O(1) on average, which means the work does not grow with the size of the set. The lesson Counting steps explains O(1) and O(n).
| Names stored | List: is kai here? (no) | Hash set: is kai here? (no) |
|---|---|---|
| 10 | 10 looks | a few steps |
| 1,000 | 1,000 looks | a few steps |
| 1,000,000 | 1,000,000 looks | a few steps |
What a set gives up
A set is not better than a list at everything. It gives up three things.
- Positions. A set has no first item or third item, so you cannot write
guests[0]. - Order. A set does not remember the order in which you added things.
- Repeats. If you need to keep the same value twice, such as two equal scores in a game, a set keeps only one.
So use a set when your main question is "do I have this?" or "has this happened already?". Use a list when order, positions or repeats matter.
Check yourself
Which question is a set built to answer?
A set starts empty. You add amir, then bea, then amir again. What does the set hold?
What do the two print lines show?
colours = set()colours.add("red")colours.add("blue")colours.add("red")print(len(colours))print("blue" in colours)Set<String> colours = new HashSet<>();colours.add("red");colours.add("blue");colours.add("red");System.out.println(colours.size());System.out.println(colours.contains("blue"));What comes next
You can now use a set. The next lesson looks inside it to see where the speed comes from.
A hash set uses the same idea as a hash map. A hash map stores pairs: a key and a value, such as a name and a phone number. A hash set stores the keys and no values. So "what is Bea's phone number?" is a question for a map, and "is Bea on the list?" is a question for a set.
The next lesson begins with a short reminder of how a hash map works. If hash maps are new to you, the tutorial Hash Maps & Hashing teaches them from the start.
- Say what a set is: a collection that holds each item once and can tell you whether it holds an item.
- Say what a membership test is: the question, is this item in the set?
- Add to a set, remove from it and ask it questions in Python or Java.
- Say when a set is the right choice, and when a list is.