Why can't I use a list as a dictionary key or set member?
Quick answer
Python requires dictionary keys and set members to be hashable. Lists are mutable containers and are not hashable, so using one in either place raises a TypeError. Use a tuple of hashable values when you need a compound key or set member. A tuple containing a list is not a workaround: every element in the tuple must be hashable too. [S1]
The question, the details, the next step.
A practical checklist
Identify the exact value being used as the dictionary key or set member.
If it is a list, choose a hashable representation instead of inserting the list.
For a compound value, consider a tuple only when every element is hashable.
Inspect nested tuple elements; a list inside a tuple is still unhashable.
Confirm that the replacement representation matches what should identify the entry.
A few more useful answers
Can I use a tuple as a dictionary key every time?
No. A tuple is hashable only if all of its elements are hashable. A tuple containing a list is not a valid dictionary key. [S1]
Can a list be a member of a set?
No. Lists are mutable and unhashable, while set members must be hashable. Use a suitable tuple if its elements are all hashable. [S1]
Does changing a list to a tuple always preserve my program’s meaning?
Not necessarily. Use a tuple when the values should form one compound key or member; decide which values define that identity based on your data.
Sources
References used for this guide.
- [S1] Python Glossary: hashable docs.python.org · Checked
