简体   繁体   中英

Hashability and immutability doubts in Python

Sorry if this has been asked before, but I couldn't answer it by myself. I'm trying to learn Python and while I was exploring the idea that sets can't contain mutable objects. I tried different scenarios using a list inside a set and arrived to a point where I was putting a list inside a tuple inside a set , getting the following:

a = ([1,2,3],)
type(a)
<class 'tuple'>
S = {1,2,3,a}
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    S = {1,2,3,a}
TypeError: unhashable type: 'list'
c = ((1,2,3),)
type(c)
<class 'tuple'>
S = {1,2,3,c}
>>> S
{1, 2, 3, ((1, 2, 3),)}

So a and c are both tuples but one has an unhashable type inside (a list ). So, I would assume that a better statement for sets would be that they can't contain unhashable objects. Anyway, my doubt is, how does this process occur for python in terms of knowing which tuple in this case is valid to be used in a set ?

Thank you all, SP

sets require their elements to be hashable. So, mutable types are not hashable because a change of their values would change the hash and which in turn breaks the whole property of hash.

Note: if you explicitly define __hash__() then you could do for immutable types also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM