What is a set?
- Algorithms course
- Beginner
- Lesson 73/80
- 4 min
A set stores unique elements.
What is a set?
A set is a data structure that stores unique elements. An element is either in the set or not; there is no ordering.
Add, remove and search in a set are average O(1). Duplicates are automatically eliminated: the same element cannot be added twice.
Add and search
Elements are added to a set with add(item). contains(item) checks whether an element is in the set.
A set uses a hash table to provide O(1) average access. If the element already exists, add does nothing.
Practice Add to set
Write set_add(s, item). Add item to s, return s. Print {1, 2, 3} with print(set_add({1, 2}, 3)).
Starter code
def set_add(s, item):
# AddSample solution
def set_add(s, item):
# Add
s.add(item)
return s
print(sorted(set_add({1, 2}, 3)))Expected output
[1, 2, 3]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What property does a set have?
- Fixed size
- Unique elements Correct answer
- Ordered
- Duplicate elements
Explanation: A set has unique elements.
2 Add
Adding to a set is done with ____.
Adding to a set is done with add.
Explanation: add is right.
3 What is a set: match the terms
| Term | Meaning |
|---|---|
set |
Unique |
add |
Add |
contains |
Exists |
O(1) |
Average |