This quiz question tests your understanding of how default mutable arguments in Python functions work.
This concept is crucial for avoiding unexpected behavior in Python programs.
Contents
Question: Default Mutable Arguments in Python
What will be the output of the following Python code and why?
def func(x, y=[]):
y.append(x)
return y
print(func(1))
print(func(2))
print(func(3, []))
print(func(4))Answer: B
Explanation:
When you call func(4), it again uses the default list y, which is still [1, 2]. Thus, 4 is appended to y, making y = [1, 2, 4].
When you call func(1), it uses the default value for y, which is an empty list []. The function appends 1 to y, making y = [1].
When you call func(2), it again uses the default list y, which is now [1] because the default argument y is mutable and retains its state across function calls. Thus, 2 is appended to y, making y = [1, 2].
When you call func(3, []), you explicitly provide a new empty list for y, so it appends 3 to this new list, resulting in y = [3].