Python Programming - Tricky Questions - Discussion

Discussion Forum : Tricky Questions - General Questions (Q.No. 7)
7.
What is the output of the following Python code?
def mysterious_function(a, b=[]):
    b.append(a)
    return b

result1 = mysterious_function(1)
result2 = mysterious_function(2)
result3 = mysterious_function(3)

print(result1 + result2 + result3)
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[1, 2, 3]
[1, 2, 3, 3, 3, 3, 3, 3, 3]
This code will result in an error.
Answer: Option
Explanation:
The mysterious_function appends the value of a to the list b and returns b. In the code, result1 is [1], result2 is [1, 2], and result3 is [1, 2, 3]. When print(result1 + result2 + result3) is executed, it concatenates the three lists, resulting in [1, 2, 3, 1, 2, 3, 1, 2, 3]. Therefore, the output of the code is [1, 2, 3, 1, 2, 3, 1, 2, 3].
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.