Sub topic 1
What a set is
Prerequisites
This chapter assumes you know basic Python syntax and variables. You should also know lists, tuples and dictionaries, how for loops and the in operator work, and the difference between mutable and immutable objects.
The working model
A set is a built-in Python collection that holds unique elements with no defined order. Two rules define it:
- Uniqueness. Each value appears at most once. Adding a value that is already present changes nothing.
- No order. A set does not record positions. You cannot index it (
s[0]raisesTypeError) or slice it, and you should not depend on the order in which it yields elements.
A set is also mutable: you can add and remove elements after creating it. Its immutable sibling, frozenset, comes in a later chapter.
fruits = {"apple", "banana", "apple"}
print(len(fruits)) # 2, duplicates are dropped
letters = set("hello")
print(len(letters)) # 4, because 'l' appears twiceThe literal {"apple", "banana", "apple"} lists three values, but the set keeps two. Calling set("hello") iterates over the string and keeps each distinct character once.
Sets compared with lists and dicts
Sets sit between lists and dictionaries. A dict stores keys with values. A set stores only the keys, so it behaves like a dict with no values.
| Feature | list | dict | set |
|---|---|---|---|
| Duplicates allowed | Yes | Keys unique | Yes, but dropped |
| Indexed by position | Yes | By key | No |
| Fast `in` test | No, scans items | Yes, on keys | Yes |
| Mutable | Yes | Yes | Yes |
Use a list when order and repeats matter. Use a set when you only care whether a value is present, or when you need to combine collections with set algebra.
Why elements must be hashable
Every element in a set must be hashable, meaning Python can compute a fixed integer fingerprint for it. Sets use that fingerprint to find elements quickly. Immutable built-in types such as numbers, strings and tuples of hashable items qualify. Mutable containers such as lists do not.
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'Later chapters cover this rule and its fixes in detail. For now, remember that putting a list inside a set literal fails with TypeError.
How the pieces fit together
Two early warnings
Empty braces create a dict, not a set. To make an empty set, call set().
empty = set() # {} would create an empty dict
print(type({})) # <class 'dict'>
print(type(empty)) # <class 'set'>Do not rely on the order in which a set prints or loops. The order can differ between runs and Python versions, so use sorted(s) when you need a predictable sequence.
Check your understanding
Exercise
What does len({1, 2, 2, 3, 3, 3}) return, and why? Also, what type does x = {} create?
Show answer
It returns 3, because a set keeps each distinct value once, leaving {1, 2, 3}. The statement x = {} creates an empty dict, not a set. Use set() for an empty set.
Exercise
Why does {[1, 2], [3, 4]} raise a TypeError, and what would you change to make it work?
Show answer
Lists are mutable and therefore unhashable, and set elements must be hashable. Replace the lists with tuples: {(1, 2), (3, 4)}.