Python Mutable vs Immutable Objects: Key Differences and Examples
In Python, mutable objects can change after they are created, while immutable objects cannot. This difference affects assignment, copying, function arguments, dictionary keys, and bugs that come from two names pointing to the same object. The sections below show the practical differences, the mistakes people make, and how to predict what Python will do.
Difficulty: Beginner
Helpful to know first: basic Python variables, how functions work, and the difference between a value and a variable name.
- Use mutable objects when you need to edit the same object in place.
- Use immutable objects when values should not change after creation.
- Be careful with aliasing: two variables can refer to the same mutable object.
| Topic | Mutable | Immutable |
|---|---|---|
| Can the object change in place? | Yes | No |
| Common examples | list, dict, set | int, float, str, tuple |
| Typical use | Build and update collections | Store fixed values, use as keys, avoid accidental changes |
| Common surprise | One change can be seen through another name | A “change” usually creates a new object instead |
How Mutable and Immutable Objects Behave in Python
Python names do not store values directly. A variable name points to an object, and the object may or may not allow changes. If the object is mutable, operations like append, item assignment, or update change the same object. If the object is immutable, any apparent change creates a new object.
Here is the smallest useful example:
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
name = "Ada"
# name[0] = "M" # TypeError: 'str' object does not support item assignment
The list changes in place, so the same object now contains four items. The string cannot be changed character by character, so Python prevents item assignment.
Use Mutable Objects When the Data Must Change
Mutable objects are useful when you need to add, remove, or update values without creating a new object every time. Lists are the most common example. Dictionaries and sets are also mutable, which makes them practical for growing collections and lookup tables.
Updating a list in place
When you call a list method like append, the list itself changes. Any variable that refers to that list sees the updated contents.
shopping_list = ["milk", "bread"]
shopping_list.append("eggs")
print(shopping_list) # Output: ['milk', 'bread', 'eggs']
This works well because the goal is to keep expanding the same list.
Changing a dictionary entry
A dictionary is mutable because you can add new keys and replace existing values. That makes it a natural choice for data that changes over time.
student = {"name": "Mina", "score": 91}
student["score"] = 95
print(student) # Output: {'name': 'Mina', 'score': 95}
The dictionary keeps the same identity, but one of its values changes.
Why mutation matters for shared references
If two names point to the same mutable object, a change through one name is visible through the other. This is a normal Python behavior and a common source of confusion.
a = [1, 2]
b = a
b.append(3)
print(a) # Output: [1, 2, 3]
print(b) # Output: [1, 2, 3]
Both names refer to one list, so there is only one object to update.
Use Immutable Objects When You Need Stability
Immutable objects are a good fit when you want values that stay fixed after creation. Python uses immutability for many built-in scalar types such as int, float, bool, and str. Tuples are also immutable, even though they can contain mutable objects inside them.
Strings do not change character by character
A string looks like a sequence of characters, but you cannot modify one character in place. You create a new string instead.
word = "cat"
word = "b" + word[1:]
print(word) # Output: bat
The old string "cat" was not edited. Python built a new string and stored it in the same variable name.
Tuples keep their structure fixed
Tuples are useful for fixed records, such as coordinates or database-like rows. The tuple object itself cannot grow or shrink.
point = (3, 4)
print(point[0]) # Output: 3
# point[0] = 10 # TypeError: 'tuple' object does not support item assignment
The tuple can be read, but not edited. That makes it safer when you do not want accidental changes.
Immutable values can be reused internally
Python may reuse some immutable objects for efficiency, especially small integers and some strings. That does not change the rule: if the type is immutable, you cannot change that object in place. If you write a new value, you get a new object.
x = 10
y = x
y = 11
print(x) # Output: 10
print(y) # Output: 11
Changing y does not affect x, because integers are immutable.
The Difference Between Changing an Object and Rebinding a Name
A lot of confusion comes from mixing up two different actions. Mutating an object changes the object itself. Rebinding a name makes the name point to a different object.
For a mutable object, both actions are possible. For an immutable object, only rebinding is possible.
items = [1, 2]
items.append(3)
print(items) # Output: [1, 2, 3]
text = "hi"
text = text + "!"
print(text) # Output: hi!
The list method changes the same list object. The string concatenation creates a new string and rebinds text to it.
Predict the Output
Two names pointing to the same list
What does this print?
a = [1]
b = a
b.append(2)
print(a, b)
Show answer
It prints [1, 2] [1, 2]. The assignment b = a does not copy the list. Both names point to the same mutable object, so append changes what both names see.
A default list that keeps growing
What happens when this function is called twice?
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1))
print(add_item(2))
Show answer
It prints [1] and then [1, 2]. The default list is created once when the function is defined, not each time the function is called. Because the list is mutable, the second call sees the item added by the first call.
Common Mistakes When Working With Mutable and Immutable Values
Copying a list by assignment instead of making a new list
Many beginners expect = to copy a list. It does not. It only creates another name for the same object.
Problem: The code changes one list and is surprised that the other variable changes too.
first = [1, 2]
second = first
second.append(3)
print(first) # Output: [1, 2, 3]
Fix: Use copy() or slicing when you want a separate list.
first = [1, 2]
second = first.copy()
second.append(3)
print(first) # Output: [1, 2]
print(second) # Output: [1, 2, 3]
The fixed version works because the two variables now refer to different list objects.
Using a mutable default argument
A function default is evaluated once, so a mutable default value can keep data between calls.
Problem: The list stored in the default argument is reused every time the function runs, so old data leaks into new calls.
def add_name(name, names=[]):
names.append(name)
return names
print(add_name("Ava"))
print(add_name("Noah"))
Fix: Use None as the default and create a new list inside the function.
def add_name(name, names=None):
if names is None:
names = []
names.append(name)
return names
print(add_name("Ava"))
print(add_name("Noah"))
The corrected version creates a new list each time no list is supplied.
Expecting a tuple to protect nested mutable data
Tuples are immutable, but the objects inside them may still be mutable. That means a tuple can hold a list whose contents change.
Problem: The tuple itself cannot be reassigned, but the list inside it can still be edited.
record = ("team", ["A", "B"])
record[1].append("C")
print(record) # Output: ('team', ['A', 'B', 'C'])
Fix: Use an immutable object for the nested value too, such as another tuple, if you need the whole structure to stay fixed.
record = ("team", ("A", "B"))
# record[1].append("C") # AttributeError: 'tuple' object has no attribute 'append'
print(record) # Output: ('team', ('A', 'B'))
The corrected version works because the nested tuple cannot grow or change either.
Find the Bug
Here is a function that is supposed to collect tags from multiple calls. It looks reasonable, but it has a subtle bug related to mutability. Find it.
def collect_tags(tag, tags=[]):
tags.append(tag)
return tags
print(collect_tags("python"))
print(collect_tags("lists"))
Show answer
The bug is the mutable default argument. The same list is reused for every call, so the second result includes the first tag. A fixed version uses None and creates a new list inside the function.
def collect_tags(tag, tags=None):
if tags is None:
tags = []
tags.append(tag)
return tags
print(collect_tags("python"))
print(collect_tags("lists"))
The fixed version works because each call gets its own new list unless one is explicitly passed in.
When to Use Mutable and Immutable Types
Choose based on whether the value needs to change and whether shared state is helpful or harmful. A mutable type makes sense for a growing collection or a record that you update in place. An immutable type makes sense for values that should stay stable, be hashable, or be safe to share without accidental edits.
| If you want to... | Use | Example |
|---|---|---|
| Store an ordered collection you will edit | list | Todo items, names, scores |
| Store a fixed record | tuple | Coordinates, RGB values |
| Map keys to values that change over time | dict | User profiles, settings |
| Keep a value stable and hashable | str, int, tuple | Dictionary keys, set members |
Sometimes the best choice is a mix. For example, a tuple can contain a list when the outer shape should stay fixed but one inner collection should grow. That is valid Python, but it is easy to misunderstand.
Mutable or immutable when passing data to functions
If a function should update a collection in place, pass a mutable object and document that behavior. If a function should not change the caller’s data, either use immutable inputs or make a copy inside the function before editing.
def add_bonus(scores):
scores.append(100)
values = [70, 80]
add_bonus(values)
print(values) # Output: [70, 80, 100]
This is helpful when mutation is the point. It is a bad fit when the caller expects the original object to stay unchanged.
Common Questions Interviewers Ask About Mutability
Why are strings immutable in Python?
Strings are immutable because they are used heavily, shared often, and optimized for safety and efficiency. Immutability also makes strings usable as dictionary keys and set elements.
Why is a tuple immutable if it can contain mutable items?
The tuple container itself cannot change size or replace its slots, but Python does not freeze the objects stored inside it. If a slot refers to a list, that list can still change.
Why does mutability matter for dictionary keys?
Dictionary keys must be hashable, and hashable objects must not change in ways that affect their hash value. Mutable built-in containers like lists are not hashable, so they cannot be used as dictionary keys.
Try It Yourself
Write a function that adds a score to a list of scores without changing the original list.
- Create a function named add_score.
- The function should take two arguments: a list of scores and one new score.
- Return a new list that contains the old scores plus the new score.
- Do not modify the original list.
Expected output:
[10, 20]
[10, 20, 30]Hint: Make a copy of the list before you add the new score.
Show solution
def add_score(scores, new_score):
updated_scores = scores.copy()
updated_scores.append(new_score)
return updated_scores
original = [10, 20]
result = add_score(original, 30)
print(original) # Output: [10, 20]
print(result) # Output: [10, 20, 30]
Summary
- Mutable objects can change in place; immutable objects cannot.
- Lists, dictionaries, and sets are mutable.
- Integers, floats, strings, and tuples are immutable.
- = binds a name to an object; it does not copy the object.
- Aliasing is a major source of bugs with mutable objects.
- Mutable default arguments are a common mistake and should usually be avoided.
Next, study Python copy vs reference so you can see when to use shallow copies, deep copies, and shared references.