Fixing Mutable Default Arguments
In Python, using mutable objects like lists as default arguments in functions can lead to unexpected behavior. This happens because the default value for a function argument is only evaluated once, at the time when the function is defined. Consequently, the mutable default argument is shared between all function invocations.
To overcome this, the function should be modified to use
None
as the default value for the list argument and then initialize an empty list inside the function when this argument is None
.You are required to modify the
mutable_default_argument
function defined in the previous exercise. This function will take two parameters: an integer n
and a list lst
that defaults to None
.The function should check if
lst
is None
and if so, initialize it as an empty list. It should then append the integer n
to lst
and return lst
.The first line of the input contains a single integer
m
, the number of times the function will be called. Each of the next m
lines contains a single integer n
, the number that will be appended to the list.The output should contain
m
lines. Each line should be a list, representing the state of lst
after each function call.Input | Output |
3
1
2
3 | [1]
[2]
[3] |
Note: Observe how, unlike in the previous exercise, the list
lst
is not shared across function invocations. Each function call produces a list with a single element, corresponding to the number appended in that particular call. This is the expected behavior and is achieved by avoiding the use of mutable default arguments.Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB