In: Computer Science
Part 1
Here is some code:
def foo(var):
var = [] var.append("hello") var.append("world") list = ["bah"] foo(list) print(list)
Which Option is correct?
A) ["hello","world"] is output because python passes the list by reference and the list is changed inside the function.
B) ["bah"] is output because python passes the list by value so changes to the list in the function are made to a separate list than the one that is passed in.
C) ["bah"] is output because python passes the list by reference but a new reference is created by the first line in the function so subsequent changes are made to a separate list than the one that is passed in.
Part 2
Consider this code:
list1 = []
list2 = list1
list2.append(1)
list2.append(2)
list1.append(3)
Which option is correct?
A) list1 contains [3] and list2 contains[1,2]
B) list1 contains [3] and list2 references the same list as list1
C) list1 contains [1,2,3] and list2 references the same list as list1
D) list2 contains [1,2,3] and list1 also contains [1,2,3] but the 3 is stored in a different location than list2
Part 1-
def foo(var):
var = []
var.append("hello")
var.append("world")
list = ["bah"]
foo(list)
print(list)
ANSWER- C) ["bah"] is output because python passes the list by reference but a new reference is created by the first line in the function so subsequent changes are made to a separate list than the one that is passed in.
EXPLAINATION- Let's first understand what is a call by reference. In call by reference the reference or address of the variable or list is passed to the function or method. And hence, any change in the variable inside the function is reflected in our main variables or more specifically called actual arguments.
Now, in python list is by default passed as call by reference that means any change in the list inside the function will be reflected in the actual arguments. But then why the output is not ["hello","world"] here. That is because the new reference is created by the first line in the function so subsequent changes are made to a separate list than the one that is passed in.
Part 2-
list1 = []
list2 = list1
list2.append(1)
list2.append(2)
list1.append(3)
ANSWER- list1 contains [1,2,3] and list2 references the same list as list1.
EXPLAINATION- In python the assignment operator makes the two list point to a single list. That means what list2=list1 does is it points the same list. So any change in either of them will be reflected in both the lists because the are referencing to same chunk of memory.
HAPPY LEARNING