def func(x=[]):
x.append(1)
return x
print(func())
print(func())
Solution and Explanation: B is the correct answer
Default Argument Behavior:
The default argument x=[] is evaluated only once when the function is defined, not each time the function is called. This means that if the default value is a mutable object like a list, it will be shared across all calls to the function.
First Function Call (print(func())):
The first time func() is called, the list x is empty because the default value ([]) is used.
Inside the function, 1 is appended to the list, so x becomes [1].
The function returns this list, which is then printed, so the output is:
Second Function Call (print(func())):
The second time func() is called, the same list x from the previous call is used, not a new empty list.
Again, 1 is appended to this list, so x becomes [1, 1].
The function returns this list, which is then printed, so the output is:
[1, 1]
Mutable Default Arguments: In Python, using a mutable object (like a list or dictionary) as a default argument can lead to unexpected behavior because it persists across function calls.
Best Practice: To avoid this, use None as the default value and then initialize the mutable object inside the function if needed.
0 Comments:
Post a Comment