Equivalent vs.
Identical in Python
In Python, equivalent objects have the same value/content, while identical objects are the same object in memory.
Example 1: Lists and Comparisons
python
list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a print(list_a == list_b) # Equivalent? True (same values) print(list_a is list_b) # Identical? False
(different objects) print(list_a is list_c) # Identical? True (same object)
Output explanation:
list_a == list_b is True because their values match.
list_a is list_b is False because they are separate objects.
list_a is list_c is True because list_c references the same object as list_a.
Objects, References, and Aliasing
Objects: Data structures in memory (e.g., ``).
References: Variables pointing to objects (e.g., list_a).
Aliasing: Multiple references to the same object.
Example 2: Aliasing and Mutability
python
original = ["apple", "banana"] alias = original # Aliasing: both
reference the same object copy = original.copy() # New object with same values alias.append("cherry")
print(original) # Output: ["apple", "banana", "cherry"] print(copy) # Output: ["apple", "banana"]
Explanation:
Modifying alias affects original because they reference the same object.
copy remains unchanged because it’s a separate object.
Function Modifying a List Argument
Example 3: In-Place List Reversal with Custom Logic
python
def mirror_modify(lst): """Reverses the list and appends its mirrored version.""" # Modify the original list in-place
lst.reverse() mirrored = lst.copy() mirrored.reverse() lst.extend(mirrored) numbers = [10, 20, 30]
mirror_modify(numbers) print(numbers) # Output: [30, 20, 10, 10, 20, 30]
Technical Breakdown:
Arguments/Parameters:
numbers is passed to mirror_modify as an argument.
lst becomes a parameter referencing the same object as numbers.
In-Place Modification:
lst.reverse() alters the original list object.
lst.extend() appends
mirrored data to the same object.
Question: How do you think Python'spass-by-object-reference behavior affects the design of functions that modify
mutable data
structures like lists?
References.
Downey, A. (2015). Think Python: How to think like a computer scientist. Green Tea Press. This book is licensed
under Creative Commons Attribution-NonCommercial 3.0 Unported