0

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.

  • The tuple contains a reference to a mutable list – Riccardo Bucco Nov 25 '21 at 11:24
  • 1
    Because you *can* still mutate the elements in the tuple, which would/should result in a different hash… – deceze Nov 25 '21 at 11:24
  • 2
    Good question. "so the hash of a tuple containing mutable objects should also not change even though the elements are allowed to change". You could compute the hash of tuples on basis of the ids of their elements. Great, now tuples with mutable elements are hashable and you can put them into sets. But now you get `False` for `a = ([1], [2]); b = ([1], [2]); a in {b}`. – timgeb Nov 25 '21 at 11:31
  • @deceze I think the dupe addresses the specific question superficially at best. – timgeb Nov 25 '21 at 11:36
  • @deceze "Hashable objects that are equal to each other should have the same hash" from the other dupe fits the question, thanks. – timgeb Nov 25 '21 at 11:40

0 Answers0