Given the following example,
class A(object):
pass
a = A()
a.x = 1
Obviously a is mutable, and then I put a in a set,
set([a])
It succeeded. Why I can put mutable object like "a" into a set/dict? Shouldn't set/dict only allow immutable objects so they can identify the object and avoid duplication?
It is one of the four built-in data types (List, Dictionary, Tuple, and Set) having qualities and usage different from the other three. It is a collection that is written with curly brackets and is both unindexed and unordered. A set is mutable, i.e., we can remove or add elements to it.
If the key were a mutable object, its value could change, and thus its hash could also change. But since whoever changes the key object can't tell that it was being used as a dictionary key, it can't move the entry around in the dictionary.
List, Sets, and Dictionary in Python are examples of some mutable data types in Python. Immutable data types are those, whose values cannot be modified once they are created. Examples of immutable data types are int, str, bool, float, tuple, etc.
As shown in the figure below, keys are immutable ( which cannot be changed ) data types that can be either strings or numbers. However, a key can not be a mutable data type, for example, a list. Keys are unique within a Dictionary and can not be duplicated inside a Dictionary.
After doing some more research, I was able to find out the reason why I would think set and dict only allow immutable objects as the entries and keys respectively, which is incorrect. I think it's important for me to clarify that here as I'm sure there are people who are new to Python having the same doubt as I had before. There are two reasons for me to previously confuse immutability with hashability. First reason is that all the built-in immutable objects (tuple, frozenset...) are allowed as set entries or dict keys, while all of the built-in mutable container objects are not. Second reason is actually where this question was derived from. I was reading the book Mastering Object-Oriented Python. In the part it explains the __hash__
function, it leads the reader into thinking immutability is the prerequisite of hashability.
The definition of immutability is for an object, after its creation, you can't change the value of its existing attributes or creating new ones. So it has nothing to do with hashability, which requires an object to have their __hash__()
and __eq__()
methods defined, and their hash value to be immutable during their lifecycle. Actually hashable objects are immutable in terms of their hash value. I guess that's one of the reason these two concepts get confused so often.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With