Mutable and Immutable Objects

An object is mutable when its contents can change after creation, and immutable when they cannot. Among the built-in types, lists, dictionaries, and sets are mutable; numbers, strings, tuples, and frozensets are immutable. Operations do not modify the immutable object itself, but need not allocate a new object. Use the returned result of text.replace(), for example by assigning it, while items.append() changes the existing list.

Assignment binds a name to an object and never copies it. After alias = original, both names refer to one object, so a mutation through either is visible through both, and original is alias is True. Strings cannot change in place, but an immutable container can refer to mutable objects: a list inside a tuple can still change. Tuple conversion is not a deep freeze. Rebinding one name, alias = [9], only changes where that name points.

To work on an independent collection, copy it: list(original), original.copy(), and original[:] all produce a new list. These are shallow copies, so the new container refers to the same inner objects and mutating a nested list is still visible from both. copy.deepcopy() recursively copies supported nested objects, at a time and memory cost; it preserves shared relationships through its memo and is not a universal clone of files or external resources.

Two consequences appear often in real code. First, only hashable objects can be dictionary keys or set elements, and built-in lists, dictionaries, and sets are unhashable. Hashability requires a stable hash consistent with equality; it is not synonymous with immutability. A tuple containing a list is immutable but unhashable, while custom objects may be mutable and hashable. Second, a default argument is evaluated once when the function is defined, so a mutable default such as def add(item, target=[]) accumulates values across calls; use None as the default and create the list inside the function. When passing a collection to code you do not control, consider passing a copy or an immutable type.

References: Objects, values and types, copy module. See it in use in Python Collections and Comprehensions.


Discover more from Insightful Data Lab

Subscribe to get the latest posts sent to your email.

Similar Posts

Questions, corrections, or additional insights?

This site uses Akismet to reduce spam. Learn how your comment data is processed.