What Can Be in a Set?
Concepts covered: Sets
Numbers and strings can be set members, and so can booleans. Lists and dictionaries cannot, and neither can another set. The rule behind the 2 groups is about change: a value that can be altered after it is created can't be a set member.
broken = {[1, 2], 3}The error says unhashable. Hashing is the step that turns a value into the slot number the set stores it under, the same step that lets in finish in 1 look. The message means Python declined to compute that number for a list.
Why a changing value cannot be a member
Suppose a set did accept [1, 2]. It would compute a slot from the contents 1 and 2 and file the list there. Then you run my_list.append(3). The list in the set now reads [1, 2, 3], but it still sits in the slot computed for [1, 2]. Ask [1, 2, 3] in my_set and the set looks in the slot for [1, 2, 3]. That slot is empty, so it says False about a value it holds. Rather than allow that, Python refuses to hash its built-in types that can change after creation, which includes lists and dictionaries as well as sets themselves. Integers and floats cannot be altered in place, and neither can strings or booleans, so their slot never goes stale.
| Value | Can it change after creation? | Set accepts it? |
|---|---|---|
| `42` | No | Yes |
| `2.5` | No | Yes |
| `"abc"` | No | Yes |
| `True` | No | Yes |
| `[1, 2]` | Yes, `append` and more | No |
| `{"a": 1}` | Yes, keys come and go | No |
| `{1, 2}` | Yes, `add` and `discard` | No |
mixed = {7, "seven", 7.5}
print(len(mixed))
print("seven" in mixed)
mixed.add([8])Mixed types in 1 set are fine: 3 members of 3 types. The failure comes at the add([8]) line, after the 2 prints have already run. Read the output in order: 2 printed lines, then the traceback. An error stops the program at the line that raised it, and nothing earlier is undone.
Records: store the id, keep the dict elsewhere
You'll often have a list with 1 dictionary per event and need the distinct users behind them. The dictionaries can't go in a set, and they don't need to. Pull out the field that identifies a user and add that.
events = [
{"user": 3, "action": "open"},
{"user": 5, "action": "open"},
{"user": 3, "action": "buy"},
]
users = set()
for event in events:
users.add(event["user"])
print(users)
print(len(users), "distinct users")Output:
{3, 5}
2 distinct usersUser 3 sent 2 events, and the set holds 3 once. The dictionaries stay in events, available for anything else the program needs; the set holds only what identifies them, which is all a distinct count requires.
Sets inside sets
A set can't hold a set for the same reason it can't hold a list: add and discard would change its contents after filing. Python does offer a frozen kind of set that accepts no changes and so can be a member, and the advanced sets lesson covers it. For now the rule to carry is 1 sentence: if you could change it in place, it cannot be a set member.
Which line raises an error, and why?
a = {1, 2}
a.add("3")
a.add(4.0)
a.add({5})
print(len(a))- Line 2, because a set of integers cannot take a string
- Line 3, because 4.0 is a float and floats cannot be hashed
- Line 4, because a set can change and so cannot be a member
- No line fails, and the program prints 5
The error in that question has a common cousin. You hold a set and a list of new values for it, and you pass the whole list to add. Python reads that as a request to store the list itself as 1 member, and a list can change, so the call raises TypeError: unhashable type: 'list'. What you meant was to store each item of the list, which is the job update does.
codes = {"NYC", "SFO"}
new_codes = ["LAX", "SFO"]
codes.update(new_codes)
print(len(codes))This prints 3: "LAX" joins and "SFO" was already there. Written as codes.add(new_codes), the same program stops at line 3 and never reaches the print.
About this lesson
This section is part of the Sets: Beginner lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.