What is the difference between mutable and immutable types? Give examples.
BeginnerConceptLanguage essentials & functions
Answer
A mutable object can change in place after creation; an immutable one cannot, so any "change" creates a new object.
- Mutable:
list,dict,set,bytearray, most user-defined objects. - Immutable:
int,float,bool,str,tuple,frozenset,bytes.
It matters because names are references. If two variables point at the same list, appending through one is visible through the other. Only hashable (in practice, immutable) objects can be dict keys or set members.
More on Language essentials & functions
Why is Python the default scripting language in so many DevOps teams, and where would you not use it?BeginnerWhat does assignment do in Python, and how do shallow and deep copies differ?BeginnerExplain the mutable default argument bug and how to fix it.IntermediateWhat is the difference between `==` and `is`?BeginnerWhat values are "falsy" in Python, and why does it matter in scripts?BeginnerWhen do you choose a list, tuple, set or dict?Beginner