PythonPython Variables and Data TypesPython data types
What is the difference between mutable and immutable data types?
Question 32 of 88 · Updated
On this page
- 1. Mutable and immutable types compared
- 2. Mutable objects: one object, multiple names
- 3. Immutable objects: rebinding rather than mutation
- 4. Why does augmented assignment sometimes mutate and sometimes rebind?
- 5. Are tuples deeply immutable?
- 6. Assignment, shallow copy and deep copy
- 7. How does mutability affect function arguments?
- 8. The mutable default argument trap
- 9. Mutability and hashability are related, but not identical
- 10. Practical application: updating a cart without mutating its input
- 11. Common mistake: repeated nested lists
- 12. Engineering trade-offs
- Frequently asked questions
- Can an immutable variable be reassigned?
- Does an immutable operation always create a new object?
- Are all immutable objects hashable?
- Is a tuple always safe to share without modification?
- Is mutability the same as passing by reference?
- Should I always copy mutable arguments?
- Interview-ready answer
- Official references
A mutable object can be changed after it is created, whereas an immutable object cannot have its value changed in place after creation. Python lists, dictionaries, sets and bytearrays are common mutable objects. Integers, floating-point numbers, strings, tuples, bytes and frozensets are common immutable objects.
Mutability belongs to the object, not the variable name. A variable can be rebound to another object regardless of whether its previous object was mutable or immutable.
Understanding this difference helps explain shared state, function arguments, copying, augmented assignment, dictionary keys and a number of surprising Python bugs.
1. Mutable and immutable types compared#
| Property | Mutable objects | Immutable objects |
|---|---|---|
| Can change value in place? | Yes, through supported operations | No |
| Examples | list, dict, set, bytearray | int, float, complex, bool, str, tuple, bytes, frozenset, range |
| Effect of shared references | Other references can observe mutations | Rebinding one name does not alter the original object's value |
| Typical use | Updating a collection or maintaining state | Fixed values, text, records and stable keys where hashable |
| Hashability | Common mutable built-in containers are unhashable | Depends on the type and, for some containers, their contents |
| Memory and copying | May allow efficient in-place updates | Changing a value requires obtaining a different object or result |
Neither category is universally faster, safer or better. Choose a type based on the operations and invariants your program needs.
2. Mutable objects: one object, multiple names#
PYTHONitems = [1, 2] other = items other.append(3) print(items, items is other)
Output:
[1, 2, 3] TrueThe assignment other = items creates another reference to the same list. Calling append modifies that list rather than replacing the reference.
The diagram shows two snapshots of the same conceptual list object. Both names still refer to it after the append operation. The is comparison confirms the shared identity.
A similar principle applies to changing a dictionary value, adding a set element or updating a writable bytearray position.
3. Immutable objects: rebinding rather than mutation#
PYTHONa = 'cat' b = a a = a + 's' print(a, b)
Output:
cats catThe original string cannot be edited in place by concatenation. The operation produces a string result, and the assignment rebinds a to that result. The name b retains its original binding.
An attempt to assign directly to a string position, such as s[0] = 'b', raises TypeError. Similarly, assigning into a tuple position raises TypeError.
Immutability is a guarantee about an object's value, not a guarantee that every operation allocates a fresh object. Python implementations can reuse immutable objects when semantics permit.
4. Why does augmented assignment sometimes mutate and sometimes rebind?#
The syntax += does not have identical object-level behaviour for every type. Python tries the appropriate in-place operation where supported and can fall back to the corresponding ordinary binary operation, then assigns the result back to the target.
PYTHONa = [1, 2] b = a a += [3] print(a, b, a is b) x = (1, 2) y = x x += (3,) print(x, y, x is y)
Output:
[1, 2, 3] [1, 2, 3] True
(1, 2, 3) (1, 2) FalseFor the built-in list in this example, += extends the existing list, so both aliases observe the change. For the built-in tuple, concatenation produces a tuple result and rebinds x; y still refers to the original tuple.
This is a common interview question because the same syntax can have different effects depending on the operand's type.
Do not assume that every mutable type implements every operation in place or that every custom class behaves like list. Consult the type's operation contract.
5. Are tuples deeply immutable?#
Not necessarily. A tuple is an immutable sequence of references, but those references may point to mutable objects.
PYTHONrecord = ('Asha', [90, 95]) record[1].append(100) print(record)
Output:
('Asha', [90, 95, 100])The tuple's two positions still refer to the original string and list. The list itself has been modified.
The diagram represents the list before and after the mutation, not a change to the tuple's reference slot.
A tuple containing only immutable, appropriately hashable values is often suitable for a stable record. Merely converting a list to a tuple does not recursively freeze nested objects.
6. Assignment, shallow copy and deep copy#
Assignment binds another name to an object. A shallow copy generally constructs a new outer container but retains references to its elements. Deep copying recursively copies supported components, with rules that preserve sharing and handle cycles through memoization.
PYTHONfrom copy import deepcopy original = [[1], [2]] shallow = original.copy() independent = deepcopy(original) shallow[0].append(9) print(original) print(independent) print(shallow is original, shallow[0] is original[0])
Output:
[[1, 9], [2]]
[[1], [2]]
False TrueThe shallow copy is a different outer list, but its first nested list is shared with original. The deep copy creates independent nested lists in this example.
For a list with n elements, an ordinary shallow copy takes O(n) time and O(n) additional reference storage. Deep-copy costs depend on the reachable object graph, object-specific copy hooks and allocation costs. Some objects cannot be meaningfully copied, and immutable objects can be reused. Do not assume deepcopy makes every external resource or arbitrary object independent.
A dedicated copying lesson later in the curriculum examines more detailed examples and customization.
7. How does mutability affect function arguments?#
Python binds function parameters to the supplied objects. A function can mutate a mutable argument and the caller may observe the change. Rebinding the parameter alone does not rebind the caller's name.
PYTHONdef add_item(items): items.append('new') items = [] return items basket = ['old'] result = add_item(basket) print(basket) print(result)
Output:
['old', 'new']
[]The append operation changes the caller's list. The assignment items = [] creates a new local binding and leaves the caller's basket binding untouched.
This model is commonly described as call by sharing or passing object references by value. It is not traditional pass-by-reference semantics in which assigning to a parameter directly changes the caller's variable binding.
Document whether functions mutate their arguments. A caller should not have to inspect every implementation to learn whether a function unexpectedly changes shared data.
8. The mutable default argument trap#
Default argument expressions are evaluated when a function definition executes, not separately for every call that omits the argument.
PYTHONdef collect(value, items=[]): items.append(value) return items print(collect(1)) print(collect(2))
Output:
[1]
[1, 2]The default list is shared across calls. If each call should have an independent list, use a sentinel such as None and create the list inside the function.
PYTHONdef collect(value, items=None): if items is None: items = [] items.append(value) return items print(collect(1)) print(collect(2))
Output:
[1]
[2]If a caller deliberately supplies a list to the corrected function, that list is still mutated. The change addresses the unintended shared default, not all possible sharing.
Where None is a meaningful input separate from omission, a dedicated sentinel object can be more appropriate.
9. Mutability and hashability are related, but not identical#
Dictionary keys and set members must be hashable. A hashable object must have a hash value that remains stable during its lifetime, and objects that compare equal must have equal hashes.
Common mutable built-in containers such as list, dict and set are unhashable. Many immutable types are hashable, but an immutable tuple is hashable only when all its elements are hashable.
PYTHONlocations = {(3, 4): 'home'} print(locations[(3, 4)]) print({frozenset({'a', 'b'}): 'group'}[frozenset({'b', 'a'})])
Output:
home
groupBy contrast, hash([]) and hash((1, [])) both raise TypeError. The tuple in the second expression contains an unhashable list.
User-defined mutable objects can be hashable if their equality and hashing behaviour satisfies the required contract. For example:
PYTHONfrom dataclasses import dataclass @dataclass(eq=False) class Counter: count: int = 0 c = Counter() lookup = {c: 'active'} c.count += 1 print(lookup[c])
Output:
activeIn this example the class retains identity-based equality and hashing inherited from object. Updating count does not change that contract.
Avoid implementing a hash based on mutable fields that can change while an object is used as a dictionary key. Doing so can invalidate hash-based lookup assumptions.
10. Practical application: updating a cart without mutating its input#
A function can accept a list and return an updated list instead of modifying the supplied list.
PYTHONdef add_product(cart, product): return [*cart, product] original = ['pen'] updated = add_product(original, 'book') print(original) print(updated)
Output:
['pen']
['pen', 'book']This approach makes it easy to retain the previous state. It is useful in code that needs explicit state transitions, comparisons, rollback or independent snapshots.
The new outer list is a shallow construction; any nested mutable elements from cart are still shared. It is not a deep immutable snapshot.
For n existing products, constructing this new list requires O(n) time and O(n) additional reference storage. In contrast, appending to an existing built-in list is typically amortized O(1) on CPython. In-place mutation may therefore be appropriate for a large privately owned collection, whereas constructing new state can be preferable when preserving previous values is important.
11. Common mistake: repeated nested lists#
List multiplication repeats references to its elements. If an element is itself a mutable list, several positions can point to the same inner object.
PYTHONgrid = [[0] * 2] * 3 grid[0][0] = 1 print(grid)
Output:
[[1, 0], [1, 0], [1, 0]]If independent rows are required, construct each inner list separately:
PYTHONgrid = [[0] * 2 for _ in range(3)] grid[0][0] = 1 print(grid)
Output:
[[1, 0], [0, 0], [0, 0]]The comprehension creates a new row during each iteration. This is an important distinction for matrices, dynamic-programming tables and simulations.
12. Engineering trade-offs#
Use mutable objects when updates are frequent, ownership is clear and in-place changes are part of the intended interface. For example, accumulating records in a private list is often efficient.
Use immutable values when a stable representation makes the program easier to reason about. For example, coordinate tuples and immutable strings work naturally as values and, when hashable, keys.
Immutability can simplify sharing, but an immutable outer container may still expose mutable nested state. A mutable object can also be used safely when ownership, synchronization and invariants are well defined.
Neither immutability nor the Python interpreter automatically makes an arbitrary concurrent workflow thread-safe. A sequence of read-modify-write operations on shared state may need synchronization. Use appropriate locks, queues, ownership boundaries or other concurrency mechanisms according to the actual design.
Frequently asked questions#
Can an immutable variable be reassigned?#
Yes. Immutability describes the object, not the name. A name referring to an integer, string or tuple can later be bound to another object.
Does an immutable operation always create a new object?#
No. An immutable object cannot be modified in place to change its value, but an implementation may reuse an existing object when the operation permits it. Do not rely on integer or string identity caching.
Are all immutable objects hashable?#
No. A tuple containing a list is immutable as a tuple but cannot be hashed.
Is a tuple always safe to share without modification?#
Its slots cannot be replaced, but nested mutable objects may change. Review the entire reachable structure when deep immutability matters.
Is mutability the same as passing by reference?#
No. Python function parameters are bound to supplied objects. Mutation can be visible to the caller, but rebinding a parameter does not rebind the caller's name.
Should I always copy mutable arguments?#
No. Copy when independence is part of the required behaviour. Copying can cost time and memory, and a shallow copy may not provide the intended isolation.
Interview-ready answer#
Mutable objects can change their value in place after creation, while immutable objects cannot. Lists, dictionaries, sets and bytearrays are mutable; integers, strings, tuples, bytes and frozensets are immutable. Python variables are names bound to objects, so assigning a new value can rebind a name without modifying its previous object. Shared references to a mutable object observe mutations, which matters when passing function arguments, using default values and copying collections. Immutability is distinct from hashability: for example, a tuple containing a list cannot be used as a dictionary key. Choose types and copying strategies according to ownership, required operations, correctness and performance.
Official references#
- Python Language Reference — Data model
- Python Language Reference — Assignment statements
- Python Standard Library — Built-in types
- Python Standard Library — Shallow and deep copy operations
- Python Tutorial — More on defining functions
- Python Glossary — Hashable
- Python Standard Library — dataclasses
Verification note: Thirteen runnable examples were executed in isolated namespaces on Python 3.13.5; all outputs matched. Four additional tests confirmed TypeError for string item assignment, tuple item assignment, hashing a list and hashing a tuple containing a list. Four Mermaid diagrams use standard fenced flowchart syntax and were manually reviewed for node references, labels and conceptual accuracy. No local Mermaid parser was available, so live rendering and parser-level validation remain unverified. Official reference links are supplied under the authorised offline research exception and were not checked live.
References
- 1.Python Language Reference — Data modeldocs.python.org
- 2.Python Language Reference — Assignment statementsdocs.python.org
- 3.Python Standard Library — Built-in typesdocs.python.org
- 4.Python Standard Library — Shallow and deep copy operationsdocs.python.org
- 5.Python Tutorial — More on defining functionsdocs.python.org
- 6.Python Glossary — Hashabledocs.python.org
- 7.Python Standard Library — dataclassesdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design