Distinguishing Between Objects and Values in Python
Distinguishing Between Objects and Values in Python
In Python, the terms "equivalent" and "identical" are used to distinguish between objects and
values. Two objects are considered equivalent if they have the same value, even if they are not
the same object in memory. On the other hand, two objects are identical if they refer to the same
memory location.
Example of Equivalent and Identical in Python Lists
# Equivalent but not identical
list1 = [1, 2, 3]
list2 = [1, 2, 3]
print(list1 == list2) # Output: True
print(list1 is list2) # Output: False
# Identical
list3 = list1
print(list1 is list3) # Output: True
In the example, list1 and list2 are equivalent because they have the same values, but they are not
identical as they refer to different memory locations. list3 is identical to list1 because it refers to
the same memory location.
Objects, References, and Aliasing
In Python, variables store references to objects rather than the objects themselves. When a
variable is assigned to another, it creates an alias, meaning both variables refer to the same
object. For example:
a = [1, 2, 3]
b = a # 'b' is now an alias for 'a'
b.append(4)
print(a) # Output: [1, 2, 3, 4]
Here, modifying b also modifies a because they refer to the same list object.
Function Modifying a List Argument
def modify_list(lst):
lst.append(4)
my_list = [1, 2, 3]
modify_list(my_list)
print(my_list) # Output: [1, 2, 3, 4]
Question for Discussion: What impact does Python's memory management have on
programming techniques when dealing with mutable and immutable objects?