Question 41 (Python Question) - Show me your reference id What is the output of the...
MathWorks technical mcq question, verified with a worked answer. Free to practise - no sign-up.
Question 41 (Python Question) - Show me your reference id
What is the output of the following code?
def foo(x):
x[0] = ['math']
x[1] = ['works']
return id(x)
q = ['math', 'works']
print(id(q) == foo(q))
Pick ONE option
Show answer & explanation
Answer: A. True
In Python, lists are passed by reference. When foo(q) is called, the parameter x refers to the same list object as q. The function modifies the list contents but does not create a new list. Since id(q) and id(x) refer to the same object, they have identical ids, so the comparison returns True.
Step-by-step Derivation:
q = ['math', 'works']creates a list object with a specific id, let's say id_value.foo(q)is called, passingqby reference. Inside foo,xis an alias for the same list object.x[0] = ['math']andx[1] = ['works']modify the list in-place; they don't create a new list object.return id(x)returns the id of the same list object, which equals id_value.print(id(q) == foo(q))comparesid(q)(which is id_value) withfoo(q)(which is also id_value).- Result:
id_value == id_valueevaluates toTrue.