Senior
What will the code with assignment and list modification (reference semantics in Python) output?
sobes.tech AI
Answer from AI
In Python, lists are mutable objects, and variables store references to these objects. When assigning one variable to another, both will refer to the same list.
Example:
list1 = [1, 2, 3]
list2 = list1 # list2 refers to the same object
list2.append(4)
print(list1) # Outputs [1, 2, 3, 4]
Here, changes through list2 are reflected in list1 because they are the same object.
If you assign a new list to a variable, the reference changes:
list2 = [5, 6]
print(list1) # [1, 2, 3, 4]
print(list2) # [5, 6]
Thus, it is important to understand that assignment copies the reference, not the object itself. To create a copy of a list, you can use methods such as:
list.copy()- slicing
list[:] - the
copymodule for deep copying.
This knowledge helps avoid unexpected side effects when working with lists and other mutable objects.