0

when i write in my code a set with a set as an element, when I run it, it returns "TypeError: unhashable type: 'set'"

Example 1:

{{"why_this_doesn´t_work?"}}

TypeError: unhashable type: 'set'

Example 2:

A={{"a","b"},{"c"}}

print(A)

TypeError: unhashable type: 'set'

why does this happens and what does hashable means?

Hasta Dhana
  • 4,699
  • 7
  • 17
  • 26
Alex
  • 39
  • 1
  • 1
  • 5
  • https://stackoverflow.com/questions/13464152/typeerror-unhashable-type-list-when-using-built-in-set-function check it – A.Najafi May 25 '19 at 03:58

2 Answers2

1

You can not add sets to a set because sets can only store immutable objects. These are objects whose values cannot be changed unless the object has been reassigned. Since you can add elements to sets in Python, sets are mutable and not immutable. This means that they have a changing hash value.

Being hashable means to have an id that can be used to refer to that object in cases of key:value pairs or just in memory.

If an object is immutable, it does not change its hash value. However, with sets the hash value is subject to change anytime that it is modified. Therefore, sets cannot contain sets in themselves because it only accepts immutable or unhashable objects.

Refer to this table if you need help with immutable and mutable objects and data types in Python: Immutable and Mutable Types in Python

MAS
  • 84
  • 8
0

Sets can only contain hashable items. It can be the built-in immutable python objects or a custom object with a defined __hash__ function.

The question that raises also, why sets force to contain hashable items and not lists ?

Sets have the property of containing unique elements. Adding an element to a set requires comparing it to the existing set elements. This operation of comparison is possible only if the objects are hashable, and they hash is unique during the lifetime of the object, so they are considered as a unique identifier to perform the __eq__ operation.