Click here to Skip to main content
15,115,667 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
since tuple is immutable, it's hash value will never change, even though it's items are allowed to change (mutate). so why sets and dictionaries can't use a tuple with mutable objects.

example code: tuple = (1, "mayank", [1, "mayank"]) set = {1, "mayank", tuple}
error: TypeError: unhashable type: 'list'

extra explanation: tuple contains the 'id' (reference) of objects which will not change throughout the lifetime of respective objects. so the hash of a tuple containing mutable objects should also not change even though the elements are allowed to change (mutate). why then dictionaries and sets can't contain tuple with mutable elements.

What I have tried:

searching the internet.
reading more about the concepts.
testing on the command line.
Updated 4 days ago

1 solution

The issue is that the set type does not allow a list as an element, due to its rule of no duplicates. As demonstrated by:
foo = {1, 'foo', [1,2,3]}

Traceback (most recent call last):
  File "C:\Users\rjmac\Documents\VSCode\Python\", line 21, in <module>
    result = pytest()
  File "C:\Users\rjmac\Documents\VSCode\Python\", line 12, in pytest
    foo = {1, 'foo', [1,2,3]}
TypeError: unhashable type: 'list'

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900