Why Immutable Objects Behave Differently as Function Parameters in Python
This article explains what immutable objects are in Python, shows how they behave when passed as function arguments through clear code examples with integers, strings, and tuples, and offers practical advice on using immutable versus mutable types to avoid unintended side effects.
1. What Is an Immutable Object?
Common immutable objects in Python include int, float, bool, str, tuple, and frozenset. Once created, these objects cannot be modified.
2. Behavior of Immutable Objects as Function Parameters
When an immutable object is passed to a function, any “modification” inside the function does not affect the external variable because the function works with a copy of the original value (actually rebinding the name to a new object).
Example 1: Integer as Parameter
def change_number(x):
print("函数内修改前 x:", x, id(x))
x += 10
print("函数内修改后 x:", x, id(x))
a = 5
print("调用前 a:", a, id(a))
change_number(a)
print("调用后 a:", a, id(a))Output shows that the external variable a remains unchanged while the function creates a new integer object for x.
Example 2: String as Parameter
def modify_string(s):
s += " World"
print("函数内的 s:", s)
text = "Hello"
modify_string(text)
print("函数外的 text:", text)The string is immutable; the concatenation creates a new string inside the function, leaving the original text unchanged.
Example 3: Tuple as Parameter (Container but Immutable)
def modify_tuple(t):
# t[0] = 99 # ❌ Error! Cannot modify tuple elements
t = (99, 100) # Reassigning a new tuple to the local variable
print("函数内的 t:", t)
tpl = (1, 2, 3)
modify_tuple(tpl)
print("函数外的 tpl:", tpl)The tuple itself cannot be altered; reassigning t only changes the local reference, leaving the original tpl unchanged.
3. Summary of Characteristics
Immutable objects passed as arguments are safe from unintended external modifications, making functions more predictable and reducing side effects.
4. Comparison: Mutable vs Immutable Objects
5. Practical Recommendations
Function design guidelines:
If you do not want a function to modify external variables, use immutable objects as parameters.
If you need to modify external data structures, use mutable objects such as lists or dictionaries.
Avoid side effects: using immutable objects can enhance code safety.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
