Sub topic 1
What a set is
Prerequisites
This chapter assumes you know the following:
- Basic Python syntax and variables.
- Lists, tuples and dictionaries, including how to create them and loop over them.
- The
forloop and theinoperator. - The difference between mutable objects (such as lists) and immutable objects (such as tuples and strings).
You do not need to know anything about sets yet. Later chapters cover creating sets, modifying them and combining them in detail. This chapter builds the working model that those chapters rely on.
The working model
A set is a built-in Python collection that stores unique elements with no defined order. Three properties follow from that description:
- Uniqueness. Adding a value that is already present changes nothing. A set never holds two equal elements.
- No positions. A set has no index and no slicing. You cannot ask for "the first element" or write
s[0]. - Hashable elements. Every element must be hashable. Roughly, this means the element is immutable enough that Python can compute a stable fingerprint for it. The reason is explained below.
The mathematical idea behind it is the same one you may know from school. A set of numbers {1, 2, 3} is the same set as {3, 2, 1}, and writing 2 twice does not make it a bigger set.
fruits = {"apple", "banana", "apple"}
print(len(fruits)) # 2, duplicates are dropped
print(fruits == {"banana", "apple"}) # True, order does not matterCompare this with the types you already know:
| Type | Ordered | Duplicates allowed | Indexable | Mutable | Typical use |
|---|---|---|---|---|---|
| `list` | Yes | Yes | Yes | Yes | A sequence of items |
| `tuple` | Yes | Yes | Yes | No | A fixed record |
| `dict` | By insertion | Keys are unique | By key | Yes | Key-to-value mapping |
| `set` | No | No | No | Yes | Unique items, fast membership, set algebra |
| `frozenset` | No | No | No | No | An immutable, hashable set |
A set behaves much like a dictionary that stores only keys. That comparison is more than a convenience, and it explains most of the set's behavior.
Why a set is unique and unordered
A set is built on a hash table. Python computes an integer called a hash for each element with the built-in hash() function. It uses that integer to decide where in an internal array the element lives. To test whether a value is already present, Python hashes it, jumps to the matching slot, and compares only the few elements stored there.
Two consequences follow:
- Uniqueness is cheap. When you add a value, Python hashes it and checks that slot. If an equal element is already there, nothing is added.
- Order is not preserved. The position of an element depends on its hash value, not on when you added it. The iteration order is therefore an implementation detail. It can differ between runs for strings, and it can change after the set grows.
A later chapter covers the hash table and performance in more depth. For now, the key point is that the data structure trades order for speed.
words = {"pear", "fig", "plum"}
for w in words:
print(w)
# The three words print in some order. Do not rely on which one.Python randomizes string hashes at startup for security reasons. If you run this script twice, the order of the words can differ. Dictionaries preserve insertion order, but sets make no such promise.
What counts as "equal"
A set decides whether two values are duplicates using both hashing and equality. Python considers two elements the same if they have the same hash and compare equal with ==.
This has some surprising results with numbers. The values 1, 1.0 and True all compare equal and hash to the same value, so a set treats them as one element.
mixed = {1, 1.0, True, "1"}
print(len(mixed)) # 2: one numeric element and the string "1"
print(mixed) # {1, '1'}The set keeps the first value it saw, which is 1. The later equal values are discarded. The string "1" is a different value, so it stays.
Which values can be elements
An element must be hashable. Immutable built-in types such as int, float, str, bool, bytes, and tuple (when everything inside the tuple is also hashable) can be elements. Mutable containers such as list, dict and set cannot.
The reason is that a hash is computed once and used to place the element. If you could change a list after inserting it, its hash would change, and Python would look in the wrong slot when you tried to find it. Refusing mutable elements avoids that problem.
points = {(1, 2), (3, 4)} # tuples are hashable
print((1, 2) in points) # True
try:
bad = {[1, 2], [3, 4]} # lists are not hashable
except TypeError as e:
print(e) # unhashable type: 'list'A tuple is hashable only if all of its contents are. (1, [2, 3]) raises the same TypeError as a list does, because the inner list is unhashable.
try:
{(1, [2, 3])}
except TypeError as e:
print(e) # unhashable type: 'list'If you need a set of sets, use frozenset for the inner sets. A later chapter covers it.
Seeing the model in action
The following example shows uniqueness, the lack of indexing, and fast membership together.
visitors = ["ana", "li", "ana", "omar", "li", "ana"]
unique_visitors = set(visitors)
print(len(visitors)) # 6
print(len(unique_visitors)) # 3
print("omar" in unique_visitors) # True
try:
print(unique_visitors[0])
except TypeError as e:
print(e) # 'set' object is not subscriptableThe call set(visitors) builds a set from any iterable. The set keeps one copy of each name. The in test works, but indexing raises TypeError because there are no positions to look up.
Mutable, but only by adding and removing
A set is a mutable object. You can add and remove elements after creating it, and its identity stays the same. You cannot change an element in place, because elements are immutable or at least hashable. To "change" an element, remove the old value and add the new one. The next chapters cover the methods for this.
s = {1, 2}
s.add(3)
print(sorted(s)) # [1, 2, 3]The sorted() call turns the set into a list with a defined order. Use it whenever you print a set and want the output to be the same every time.
Common misunderstandings
- "A set keeps the order I wrote." It may look that way for small integers, because their hashes are the integers themselves. Do not rely on it. Strings and other objects can appear in a different order from run to run.
- "
{}is an empty set." It is an empty dictionary. Writeset()for an empty set. Curly braces create a set only when they contain at least one element, written as{1, 2}. - "I can store a list in a set." You cannot. Convert it to a tuple first, for example
tuple(my_list). - "Sets are always faster than lists." Sets are faster for membership tests and removing duplicates. They use more memory per element than a list, and they cannot be indexed or sorted in place. Pick the type that matches how you use the data.
print(type({})) # <class 'dict'>
print(type(set())) # <class 'set'>The shape of the chapter sequence
The diagram shows how the ideas in this chapter connect to the later ones.
Deciding whether to use a set
Use a set when the questions you ask of the data are about presence, uniqueness or overlap:
- Does this value appear in the collection?
- Which distinct values are there?
- Which values appear in both collections, or in only one?
Use a list or tuple when position or duplicates matter, and use a dict when each item has an associated value. If you need unique items in first-seen order, a set alone is not enough. Use list(dict.fromkeys(items)), which keeps the first occurrence of each value.
items = ["b", "a", "b", "c", "a"]
print(len(set(items))) # 3, order not defined
print(list(dict.fromkeys(items))) # ['b', 'a', 'c']<br>
Exercise
What does this code print, and why? Consider the length and the type of each object. a = {1, 1.0, True} b = {} print(len(a), type(b)._name_)
Show answer
It prints 1 dict. The values 1, 1.0 and True are equal and have the same hash, so the set keeps only the first one and its length is 1. The expression {} creates an empty dictionary, not an empty set, so the type name is dict.
Exercise
You have the list data = [["x", 1], ["y", 2], ["x", 1]]. Why does set(data) fail, and how can you get the unique pairs?
Show answer
Each inner list is mutable and therefore unhashable, so set(data) raises TypeError: unhashable type: 'list'. Convert each inner list to a tuple first: set(tuple(pair) for pair in data). The result is {("x", 1), ("y", 2)}, with the duplicate pair removed.