Python Programming - Tricky Questions - Discussion

Discussion Forum : Tricky Questions - General Questions (Q.No. 27)
27.
What is the output of the following Python code?
def func(x, y=[]):
    y.append(x)
    return y

result1 = func(1)
result2 = func(2)

print(result1 + result2)
[1, 2]
[1, 2, 1, 2]
[1, 2, 2]
[1, 2, 1, 2, 2]
Answer: Option
Explanation:
The code defines a function called func that takes two parameters: x and y. The default value for y is an empty list [].
Inside the func function, the value of x is appended to the list y using the append() method. Then, the modified y list is returned.
In the code, result1 is assigned the result of calling func(1). Since y is not provided as an argument, it uses the default value of []. Therefore, result1 is [1].
Similarly, result2 is assigned the result of calling func(2). Again, y is not provided as an argument, so it uses the default value of []. However, since the default value is a mutable object (a list), it retains its state from previous function calls. Therefore, result2 is [1, 2].
When result1 + result2 is evaluated, it concatenates the two lists, resulting in [1, 2, 1, 2].
Finally, [1, 2, 1, 2] is printed to the console as the output of the code.
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.