a guest Oct 21st, 2019 64 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Interview question: **What function can you use to show that a certain data type is mutable?**
  3. The given answer is: **The id function can be used to check if a given variable is mutable or not.**
  5. ... How? The [id]( function basically returns the memory address of the object, so, how can we tell whether an object is mutable or not by using id()?
  7. Let's define immutability.
  9. [immutable](
  11. > An object with a fixed value. Immutable objects include numbers, strings and tuples. Such an object cannot be altered. A new object has to be created if a different value has to be stored. They play an important role in places where a constant hash value is needed, for example as a key in a dictionary.
  12. ### Builtin objects.
  14. **Mutable**: list, dict ...
  16. **Immutable**: int, float, str, tuple...
  18. Only immutable objects can be used as dictionaries keys, in order to compare the keys, the objects are hashed and compared, could we say that hashable objects are inmutable?
  20. Most of Python’s immutable built-in objects are hashable; mutable containers (such as lists or dictionaries) are not; immutable containers (such as tuples and frozensets) are only hashable if their elements are hashable. Objects which are instances of user-defined classes are hashable by default. They all compare unequal (except with themselves), and their hash value is derived from their id().
  22. Looks like yes, hashable objects are immutable but...
  24. [Python data model](
  25. >
  26. > The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.)
  27. **> An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.**
  29. So, a given object is inmutable if it can be hashed. Well, it is not always true. You can still have a user defined class that is hashable and mutable by modifying `__hash__ and __eq__`
  31. **Proposed answe**r: 'You can usually use the function hash() to check an object mutability, if it is
  32. hashable it is immutable, although this does not always work as intended as user defined objects might be mutable and hashable'
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand