Let's break down the code step by step to explain what happens in the modify_list function and why the final result of print(my_list) is [1, 2, 3, 4].
def modify_list(lst, val):
lst.append(val)
lst = [100, 200, 300]
my_list = [1, 2, 3]
modify_list(my_list, 4)
print(my_list)
Step-by-step Explanation:
Function Definition: The function modify_list(lst, val) accepts two arguments:
lst: a list passed by reference (so modifications within the function affect the original list unless reassigned).
val: a value that will be appended to the list lst.
Initial State of my_list: Before calling the function, the list my_list is initialized with the values [1, 2, 3].
Calling the Function:
modify_list(my_list, 4)
We pass the list my_list and the value 4 as arguments to the function.
Inside the function, lst refers to the same list as my_list because lists are mutable and passed by reference.
First Line Inside the Function:
lst.append(val)
lst.append(4) adds the value 4 to the list.
Since lst refers to the same list as my_list, this operation modifies my_list as well.
At this point, my_list becomes [1, 2, 3, 4].
Reassignment of lst:
lst = [100, 200, 300]
This line creates a new list [100, 200, 300] and assigns it to the local variable lst.
However, this reassignment only affects the local variable lst inside the function. It does not modify the original list my_list.
After this line, lst refers to the new list [100, 200, 300], but my_list remains unchanged.
End of the Function: When the function finishes execution, lst (which is now [100, 200, 300]) is discarded because it was only a local variable.
my_list retains its modified state from earlier when the value 4 was appended.
Final Output:
print(my_list)
When we print my_list, it shows [1, 2, 3, 4] because the list was modified by lst.append(val) but not affected by the reassignment of lst.
Key Takeaways:
List Mutation: The append() method modifies the list in place, and since lists are mutable and passed by reference, my_list is modified by lst.append(val).
Local Reassignment: The line lst = [100, 200, 300] only reassigns lst within the function's scope. It does not affect my_list outside the function because the reassignment creates a new list that is local to the function.
Thus, the final output is [1, 2, 3, 4].