Mutable vs Immutable Variables in Python

Lesson 16: Mutable vs Immutable Variables in Python
When you create variables in Python, they are stored in memory — but not all variables behave the same way when you try to modify them. Understanding the difference between mutable and immutable objects is essential for writing predictable and bug-free code.
1. What Does Mutable and Immutable Mean?
- Immutable: Such variable, once created, the value cannot be changed. Instead, any modification creates a new object in memory.
Examples include:
- Numbers (
int
,float
) - Strings
- Tuples
- Booleans
Contrast to Mutable Variables :
The value can be changed after creation without creating a new object.
Examples include:
- Lists
- Dictionaries
- Sets
Example 1: Immutable Variables
# Strings are immutable
s = "hello"
print(id(s)) # memory address before change
s = s.upper() # creates a NEW string
print(s) # Output: HELLO (is a new string created)
print(id(s)) # memory address changes
When you call .upper()
, Python creates a new string object because strings cannot be modified in place. That’s why the memory address (id)
changes.
Example 1: Mutable Variables
# Lists are mutable
lst = [1, 2, 3]
print(id(lst)) # memory address before change
lst.append(4) # modifies the same list
print(lst) # Output: [1, 2, 3, 4] (same list updated)
print(id(lst)) # memory address remains the same
Here, the append()
method modifies the same list rather than creating a new one.
This is why mutable objects are often used when you want to update or store multiple values dynamically.
Why It Matters in Python
- For performance, Mutable objects can be updated efficiently without creating new copies.
- Never use mutable objects as default arguments in functions unless you intend to share state.
Example: Mutable Default Argument Trap
def add_item(item, collection=[]):
collection.append(item)
return collection
print(add_item(1)) # [1]
print(add_item(2)) # [1, 2] — same list reused!
Fix:
def add_item(item, collection=None):
if collection is None:
collection = []
collection.append(item)
return collection
Output:
print(add_item(1)) # [1]
print(add_item(2)) # [2]
In short:
Immutable objects are safe and predictable, while mutable ones are flexible but can lead to side effects if not handled carefully.
Now that you understand Mutable and Immutable Variables in Python, your next step is to learn about Constant in Python in detail.