A Python developer is confused because when they pass a list to a function and modify it, the original list changes. But when they do the same with a number, the original number doesn't change. They've provided the following code examples demonstrating this behavior:
1# Integer example 2def modify_number(num): 3 num = num + 1 4 print(f"Inside function (number): {num}") 5 6my_number = 10 7modify_number(my_number) 8print(f"Outside function (number): {my_number}") 9# Expected Output: 10# Inside function (number): 11 11# Outside function (number): 10 12 13# List example 14def modify_list(lst): 15 lst.append(4) 16 print(f"Inside function (list): {lst}") 17 18my_list = [1, 2, 3] 19modify_list(my_list) 20print(f"Outside function (list): {my_list}") 21# Expected Output: 22# Inside function (list): [1, 2, 3, 4] 23# Outside function (list): [1, 2, 3, 4]
Based on this scenario, answer the following questions:
Part A: Explain Python's "pass-by-object-reference" (also known as "pass-by-assignment") memory model. Clearly define what a "reference" is in this context, and how variables store references to objects in memory. Distinguish between mutable and immutable objects in Python and explain their significance in argument passing. (10 points)
Part B: Using the integer example from the scenario, provide a detailed step-by-step explanation of what happens in memory. Describe the state of variables, objects, and references before the function call, during the function execution, and after the function returns. Crucially, describe what a conceptual diagram depicting this process would look like, showing variable names pointing to object IDs in memory, and how re-assignment inside the function affects the local variable but not the original object referenced by the caller. (15 points)
Part C: Using the list example from the scenario, provide a detailed step-by-step explanation of what happens in memory. Describe the state of variables, objects, and references before the function call, during the function execution, and after the function returns. Crucially, describe what a conceptual diagram depicting this process would look like, showing how both the caller's variable and the function's parameter initially refer to the same list object, and how modifications to that object via the function's parameter are reflected outside the function. Also, explain what would happen if the list parameter itself were re-assigned to a new list inside the function. (15 points)
Part D: Discuss the implications of Python's argument passing model for writing robust and predictable code. Suggest best practices for handling mutable arguments to avoid unexpected side effects, such as defensive copying. (10 points)