Mutable or Immutable?
In Python, data types fall into two categories: mutable and immutable.
- Mutable types can be changed after they are created;
- Immutable types cannot be changed after creation β any "change" creates a brand new object in memory.
Immutable Types
Types like int, float, str, and tuple are immutable. That means if you "change" a variable holding one of these types, Python actually creates a new object under the hood.
# Assign an integer value to var1 var1 = 40 print("var1 =", var1) # Output: var1 = 40 print("ID of var1:", id(var1)) # Shows the memory ID of the value 40 # Reassign a new integer value to var1 var1 = 50 print("var1 =", var1) # Output: var1 = 50 print("New ID of var1:", id(var1)) # Shows a different ID β it's a new object in memory
Even though we're reusing the same variable name (var1
), the id()
function shows that the variable is pointing to a completely new object after reassignment. Thatβs because integers are immutable β they cannot be modified in-place.
Mutable Types
On the other hand, types like list
and dict
are mutable. They can be changed without creating new objects.
Swipe to start coding
Imagine you are managing a budget for a small project. Initially, your available budget is set to $100. Later, you receive an additional funding of $50.
Your task is to:
- Print the initial value of
project_budget
and its memory ID using theid()
function. - Update the value of
project_budget
to reflect the total amount. - Print the updated value and its new ID.
This will help you see how immutable types like int
behave when reassigned.
Once you've completed this task, click the button below the code to check your solution.
Solution
Thanks for your feedback!