Q3. Consider the following Python function:
def maf(x): """ (list)->bool """ temp = x temp.reverse() if temp == x: return True else: return False
If we call the function maf with the list a and then with the list b with the values give bellow:
a = [17, 38, 10, 25, 72]
b = [10, 30, 20, 30, 10]
What is the value returned by each call?
Answers (choose one):
a) maf(a) returns True and maf(b) returns True
b) maf(a) returns True and maf(b) returns False
c) maf(a) returns False and maf(b) returns True
d) maf(a) returns False and maf(b) returns False
I don’t understand why the answer is a). in my understanding, only the temp variable changes while the x stays the same. thys why is the output true in both cases ?
I went to python after and wrote this :
x = [17,2,1] temp = x temp.reverse() print(temp) print(x)
The output was this :
[1, 2, 17]
[1, 2, 17]
why did x also get reversed when we only reversed temp ?
please give me a detailed explanation.
Advertisement
Answer
The short answer to that is mutability in python (here’s a good URL to read up more about it: https://www.mygreatlearning.com/blog/understanding-mutable-and-immutable-in-python/). I’ll try my best to explain in short terms.
When you assign a variable in python using the following syntax:
a = [1, 2, 3] temp = a
Under the hood, python is simply using a pointer to refer to the same memory address that stores the created list. This can be seen using the in-built id
function in python:
id(a) id(temp)
The id
function returns the identity (or memory address for Cython, the default Python installation) of the object. You will see that the memory addresses for both variables are the same, meaning they are pointing to the same list even though they are different variables.
Thus, when you call .reverse()
on the variable a
, the list gets updated in place (you can call id
again after calling reverse
, notice that the memory address of a
before and after the reverse
function is the same). Since the variable temp
also refers to the same memory address, temp
is also now referring to the reversed list.