Skip to main content
Home/Blog/Python/Mutable vs Immutable Objects in Python: Lists, Tuples, Strings Explained
Python

Mutable vs Immutable Objects in Python: Lists, Tuples, Strings Explained

Understand the critical differences between mutable and immutable objects in Python. Learn which data types are mutable (lists, sets, dictionaries) vs immutable (strings, tuples, integers), with practical examples and performance optimization tips.

Mutable vs Immutable Objects in Python: Lists, Tuples, Strings Explained

Python objects split into two groups: mutable objects (list, dict, set, bytearray) can be changed in place after creation while keeping the same identity, and immutable objects (int, float, bool, str, bytes, tuple, frozenset) cannot be changed at all — any operation that looks like a modification actually creates a brand-new object at a new memory address. The practical test is id(): if an operation leaves the object's id() unchanged, it was mutated in place; if the id() changes, a new object was created. This single distinction drives dictionary-key rules, function-argument surprises, thread safety, and the O(n²) string-concatenation trap.

That's the summary an AI Overview will give you. Here's what it can't show you: the exact side-by-side of every type, a decision matrix for which to reach for, an animated view of what id() is actually doing under the hood, and the tuple-of-a-list edge case that breaks the tidy "tuples are immutable" rule. Let's dig in.

Mutable vs immutable at a glance

PropertyImmutable objectsMutable objects
Built-in typesint, float, complex, bool, str, bytes, tuple, frozensetlist, dict, set, bytearray
Can change in place?No — every "change" makes a new objectYes — contents change, identity stays
id() after modificationChanges (new object)Stays the same
Hashable / usable as dict keyYes (unless it nests a mutable object)No — raises TypeError: unhashable type
Thread safetySafe to share; no mid-flight mutationNeeds locking under concurrency
Memory behaviorNew allocation per changeReused buffer; in-place growth
Aliasing riskLow — sharing is harmlessHigh — two names, one object, silent side effects
When to reach for itKeys, constants, config, thread-shared values, anything you want frozenAccumulators, buffers, caches, anything you mutate in a loop

Which Objects in Python are Immutable?

Immutable objects cannot be modified after creation. Any operation that appears to change an immutable object actually creates a new object in memory. The following Python data types are immutable:

  • bool – Boolean values (True, False)

  • integer – Whole numbers

  • float – Decimal numbers

  • tuple – Ordered collections that cannot be changed

  • string – Text sequences

  • frozenset – Immutable version of sets

💡 Key Insight: Immutable objects provide memory safety and can be used as dictionary keys or set elements because their hash values never change.

Which Objects in Python are Mutable?

Mutable objects can be modified in place without creating new objects in memory. This makes them more memory-efficient for operations that involve frequent changes. The primary mutable data types in Python include:

  • list – Ordered collections that can be modified

  • set – Unordered collections of unique elements

  • dictionary – Key-value pairs that can be updated

These objects maintain their identity in memory even when their contents change, making them ideal for scenarios where you need to frequently add, remove, or modify elements.

The tuple-of-a-list gotcha

"Tuples are immutable" is true but incomplete. A tuple freezes its slots — you cannot add, remove, or reassign elements — but if a slot holds a mutable object, that object can still change:

t = (1, [2, 3])
t[1].append(4)        # allowed — the list inside is still mutable
print(t)              # (1, [2, 3, 4])
# t[1] = [9]          # TypeError — you cannot reassign the slot

hash(t)               # TypeError: unhashable type: 'list'

Because one of its members is mutable, this tuple is not hashable and cannot be used as a dictionary key or set element — even though the tuple wrapper itself is immutable. The rule that actually matters for keys is not "is it a tuple" but "is it hashable all the way down."

How to Test Object Mutability

Python provides the id() function to determine whether an object is mutable or immutable. This function returns the unique memory address of an object, allowing you to track whether operations create new objects or modify existing ones.

The diagram below shows the core difference. On the left, reassigning a string leaves the old object behind and points the name at a fresh object (new id()). On the right, append() grows the same list object in place — the name never moves, and the id() never changes.

How id() reveals mutability: reassignment creates a new object, in-place mutation does not Left panel: a string variable is reassigned and its pointer moves to a new object with a new id. Right panel: a list is appended to and the pointer stays on the same object with the same id.

Immutable: str Mutable: list

name s "hello" id: 4471 "how are you?" id: 9820 new object → new id() name lst ['a', 'b'] + 'c' + 'd' id: 5510 same object → same id()

Testing Immutable Objects (Strings)

Let's examine how string operations demonstrate immutability:

string1 = "hello"
print(f"Initial ID: {id(string1)}")
print(f"Type: {type(string1)}")

string1 = "how are you?"
print(f"New ID: {id(string1)}")
print(f"Type: {type(string1)}")

When you run this code, you'll notice that the id() values are different. This demonstrates that the variable string1 is actually a pointer to an object. When we assign a new string value, Python creates a new object and redirects the pointer, rather than modifying the original string object.

Testing Mutable Objects (Lists)

Now let's observe how list operations demonstrate mutability:

list1 = ['orange', 'apple', 'pear']
print(f"Initial ID: {id(list1)}")
print(f"Type: {type(list1)}")

# Modify the list in place
list1.append('grape')
print(f"After append ID: {id(list1)}")
print(f"List contents: {list1}")

# Reassigning creates a new object
list1 = ['orange', 'apple', 'pear', 'strawberry']
print(f"After reassignment ID: {id(list1)}")

The key observation here is that the id() remains the same after using append(), proving that the list object itself was modified rather than replaced. However, reassigning the entire list creates a new object with a different ID.

💡 One caveat when reading id(): CPython caches small integers (-5 to 256) and interns some short strings, so two separate literals can share an id() even when you did not intend it. That is an implementation optimization, not a language guarantee — use id() and is to reason about identity and mutation, never to compare values. For equality, always use ==.

Performance Impact and Memory Efficiency

Understanding mutability is crucial for writing efficient Python applications. The choice between mutable and immutable objects can significantly impact memory usage and execution speed, especially in applications that perform many data modifications.

String Concatenation: A Performance Anti-Pattern

Consider this common but inefficient approach to string building:

string1 = "hello"
print(f"Initial ID: {id(string1)}")

string1 = string1 + " how are you?"
print(f"After concatenation ID: {id(string1)}")
print(f"Final string: {string1}")

Each concatenation operation creates a new string object, copying all existing content plus the new content. In applications performing thousands of such operations, this becomes a significant performance bottleneck.

⚠️ Performance Warning: Repeated string concatenation in loops can cause O(n²) time complexity due to constant memory reallocation and copying.

Efficient String Building with Lists

A more efficient approach uses mutable lists for collecting string components:

fruit = []
print(f"Initial list ID: {id(fruit)}")

fruit.append('apple')
print(f"After first append: {id(fruit)}")

fruit.append('pear')
print(f"After second append: {id(fruit)}")

fruit.append('orange')
print(f"After third append: {id(fruit)}")

# Convert to string only once
result_string = " ".join(fruit)
print(f"Final string: {result_string}")

This approach maintains the same list object throughout all append operations, only creating the final string when needed. This reduces memory allocations from O(n²) to O(n), resulting in significant performance improvements for large-scale operations.

Python's Dynamic Typing vs Static Languages

Python's approach to mutability differs significantly from statically typed languages like C++. Understanding these differences helps developers leverage Python's flexibility while avoiding common pitfalls.

Static Typing Constraints

In C++, variables are strongly typed and immutable by design:

// C++ example - strongly typed
int myinteger = 5;

// This would cause a compilation error:
// string myinteger = "Hello!";  // Cannot redeclare with different type

Python's Dynamic Flexibility

Python allows variable reassignment with different types:

myint = 5
print(f"Type: {type(myint)}")  # <class 'int'>

myint = "Hello!"
print(f"Type: {type(myint)}")  # <class 'str'>

💡 Best Practice: While Python allows type changes, maintaining consistent variable types throughout your code improves readability and reduces debugging complexity.

Decision matrix: which should I reach for?

Use this to pick the right kind of object for the job instead of defaulting to whatever you typed first.

Your goalReach forWhyAvoid
Dictionary key or set membertuple, str, int, frozensetMust be hashable and stablelist, dict, set (unhashable)
Accumulate items in a looplist then "".join()In-place growth is O(n); string += is O(n²)Repeated str concatenation
A value shared across threads read-onlytuple, frozenset, str, intNo mid-flight mutation, no lock neededShared list/dict without a lock
A constant or config that must never changetuple, frozensetImmutability documents and enforces intentlist/dict (silently mutable)
A default argumentNone sentinel, build inside the functionMutable defaults persist between callsdef f(x=[]) / def f(x={})
A fixed set of allowed valuesfrozensetHashable, fast membership, cannot driftset if it must stay constant
A growable, ordered collectionlistCheap append/pop, mutate in placetuple (rebuilds on every change)
A mutable byte buffer (I/O, encoding)bytearrayEdit bytes in placebytes (immutable, copies)

The three bugs this actually causes

Definitions are easy. What sends people to search engines are the three failure modes below — all of them direct consequences of the mutable/immutable split, and all of them silent.

1. Mutable default arguments

A function's default values are evaluated once, when the def statement runs — not on each call. If a default is a mutable object, every call that omits that argument shares the same object:

def add_item(item, bucket=[]):     # evaluated once, at definition time
    bucket.append(item)
    return bucket

print(add_item("a"))   # ['a']
print(add_item("b"))   # ['a', 'b']   ← leaked from the previous call
print(add_item("c"))   # ['a', 'b', 'c']

You can see the shared object directly — it is stored on the function:

print(add_item.__defaults__)   # (['a', 'b', 'c'],)

The fix is a None sentinel, building the real default inside the body:

def add_item(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

Use if bucket is None:, not bucket = bucket or []. The or version looks tidier but is a different, buggier function: any falsy argument — an empty list the caller deliberately passed, 0, "" — gets silently discarded and replaced with a fresh list, so the caller's object never receives the append.

def broken(item, bucket=None):
    bucket = bucket or []          # discards a caller's empty list
    bucket.append(item)
    return bucket

mine = []
broken("a", mine)
print(mine)        # []  ← the caller's list was never touched

def correct(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

mine = []
correct("a", mine)
print(mine)        # ['a']

The same trap applies to {}, set(), and any mutable default — and to datetime.now(), which freezes at import time for the same reason.

2. Aliasing: two names, one object

Assignment never copies. It binds another name to the same object, so mutating through either name is visible through both:

a = [1, 2, 3]
b = a              # NOT a copy — same object
b.append(4)

print(a)           # [1, 2, 3, 4]  ← a changed too
print(a is b)      # True
print(id(a) == id(b))   # True

This bites hardest when building nested structures with multiplication, because * copies the reference, not the row:

grid = [[0] * 3] * 3        # three references to ONE inner list
grid[0][0] = 9
print(grid)                 # [[9, 0, 0], [9, 0, 0], [9, 0, 0]]

grid = [[0] * 3 for _ in range(3)]   # three distinct lists
grid[0][0] = 9
print(grid)                 # [[9, 0, 0], [0, 0, 0], [0, 0, 0]]

Note that [0] * 3 is safe: int is immutable, so sharing the references is harmless. The problem only appears when the repeated element is mutable.

Immutable objects are immune to all of this — aliasing a str or tuple is free, because nothing can mutate it out from under you.

3. Shallow vs deep copy

list(x), x[:], and copy.copy(x) all make a shallow copy: a new outer container holding the same inner objects. That is enough for a flat list and not enough for a nested one.

import copy

original = [[1, 2], [3, 4]]

shallow = copy.copy(original)      # or list(original) / original[:]
shallow[0].append(99)
print(original)     # [[1, 2, 99], [3, 4]]  ← inner list is shared
print(shallow is original)          # False — outer containers differ
print(shallow[0] is original[0])    # True  — inner lists are the same object

original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)     # recursively copies every level
deep[0].append(99)
print(original)     # [[1, 2], [3, 4]]  ← untouched
print(deep[0] is original[0])       # False

Choosing between them:

SituationUseWhy
Flat list/dict of immutableslist(x), dict(x), x[:]Nothing inside can be mutated; shallow is enough and much faster
Nested structure you will mutatecopy.deepcopy(x)Only deepcopy severs every shared reference
You want to keep sharing inner objectscopy.copy(x)Shallow copy is the correct tool, not a bug
Structure is fully immutable (tuple of str)No copy at allThere is nothing to protect against

deepcopy is not free — it walks the whole object graph and tracks already-seen objects to survive cycles. Reach for it deliberately, not by default.

The pattern behind all three

Every one of these bugs is the same mistake in a different costume: assuming an assignment, an argument pass, or a copy produced a new object when it only produced a new name for the same object. When in doubt, check with is or id() — those ask about identity, which is exactly the question at issue.

Why Understanding Mutability Matters

Mastering the concepts of mutable and immutable objects enables you to make informed decisions about data structure selection, memory optimization, and algorithm design. This knowledge becomes particularly valuable when developing applications that handle large datasets or require high-performance processing.

Performance Optimization: Choose mutable objects for frequent modifications to minimize memory allocation overhead and improve execution speed.

Memory Safety: Leverage immutable objects when you need guaranteed data integrity and thread-safe operations in concurrent applications.

By understanding which Python objects fit into each category and how they behave during operations, you can design applications that are both efficient and maintainable. This knowledge helps you avoid common performance pitfalls while taking advantage of Python's flexibility and power.

Frequently Asked Questions

Find answers to common questions

Mutable objects (lists, dicts, sets) are modified in-place—the object changes but stays at same memory location. Example: my_list = [1,2,3]; my_list.append(4) modifies the existing list object. All variables pointing to that list see the change (shared reference). Immutable objects (strings, tuples, numbers) can't be modified—any 'change' creates new object. Example: name = 'Bob'; name = 'Alice' creates new string, abandons old one. Key difference: mutable changes affect all references to object (one variable modifies list, other variables referencing same list see changes). Immutable requires creating new object (no shared modification surprises). This matters for: function arguments (modifying mutable argument affects caller's object), default arguments (mutable defaults are shared across function calls—dangerous), and dictionary keys (only immutable objects can be keys).

Dictionary keys must be immutable (hashable). Lists are mutable—you could use list as key, then modify the list, breaking the dictionary's internal hash table. Tuples are immutable—once created, can't change, so safe as dictionary keys. Example of problem with mutable keys: my_dict[my_list] = 'value' then my_list.append(5) would break dictionary (can't find key anymore because hash changed). Python prevents this by requiring immutable keys. Use tuple instead: my_dict[(1,2,3)] = 'value' works because tuple can't change. If you need dict with list-like keys: convert list to tuple (my_dict[tuple(my_list)] = 'value'). This freezes list contents as immutable tuple suitable for dictionary key.

Classic Python gotcha: def add_item(item, my_list=[]): creates ONE empty list shared across all function calls. First call: add_item(1) appends to empty list [1]. Second call: add_item(2) appends to SAME list [1,2] (not fresh empty list). Default argument is created once at function definition, reused for all calls. This surprises people expecting fresh empty list each call. Fix: use None as default, create new list inside function: def add_item(item, my_list=None): if my_list is None: my_list = []. This creates fresh list each call. Immutable defaults are safe (def func(x=0):—each call gets same number 0, but since it's immutable, can't cause shared mutation bugs). Use mutable defaults only when you intentionally want shared state (rare).

Shallow copy: new_list = old_list.copy() or new_list = old_list[:] creates new list with same items. Changes to new_list don't affect old_list. However, if list contains mutable objects (list of lists), shallow copy still shares those nested objects. Deep copy: import copy; new_list = copy.deepcopy(old_list) recursively copies everything, fully independent. Use shallow when: list contains immutable items (numbers, strings), or sharing nested objects is acceptable. Use deep when: nested mutable objects need independence (list of lists, each inner list should be separate). Common mistake: new_list = old_list doesn't copy—just creates another reference to same list (modifying new_list modifies old_list). Always use .copy() or deepcopy() for actual independent copy.

Mutable types have in-place methods: list.append() modifies list and returns None, list.sort() modifies list in-place. This is efficient (no copy needed) but surprising if you expect return value. Immutable types must return new objects: str.upper() returns new string (can't modify original), tuple has no modification methods. Some mutable types offer both: list.sort() modifies in-place (returns None), sorted(my_list) returns new sorted list (leaves original unchanged). Convention: methods that modify in-place return None (signal: they changed the object, not returning new one). Methods that return new object leave original unchanged. Check documentation: if method returns None, it probably modified object in-place. If it returns same type as input, probably returned new object.

Automate Your IT Operations

Leverage automation to improve efficiency, reduce errors, and free up your team for strategic work.