Reassigning a variable and modifying a mutable object are different operations. They can look similar at first because both may change what your program prints.
Understanding the Concept
Reassignment makes a name refer to a new value or object. In-place mutation changes the contents of an existing mutable object such as a list. If two names refer to one list, a mutation through either name is visible to both. Reassigning one name to an unrelated list does not automatically change the other name. Immutable types, such as strings, do not support the same in-place element changes.
When and Why You Would Use This
Follow the change in two stages: first append to a shared list, then reassign one name. The output makes it clear which operation affects shared data and which affects only a variable binding.
Practical Example
original_items = ["pen"]
current_items = original_items
current_items.append("pencil")
print(original_items)
current_items = ["eraser"]
print(original_items)
print(current_items)
Understanding the Example
The first two prints of original_items both show ['pen', 'pencil']; the final print shows ['eraser']. Appending changed the shared object, whereas reassignment changed only what current_items refers to.
Example Output
['pen', 'pencil']
['pen', 'pencil']
['eraser']
Try It Yourself
Rewrite the example using current_items = original_items.copy() and compare the effect of append().
Common Beginner Mistakes
- Assuming assigning a list to another name makes a copy.
- Expecting reassignment of one variable to update all aliases.
- Treating all Python types as mutable.
Key Takeaways
- Mutation changes an existing mutable object.
- Reassignment changes the binding of one name.
- Shared references matter when working with mutable collections.