def append to lst(val, lst=[]):
lst.append(val)
return lst
print(append to lst(1))
print(append to lst(2))
print(append to lst(3, []))
Correct Answer :
[1] [1,2] [3]
Solution :
The correct option is [1] [1,2] [3].
This question tests our understanding of default argument evaluation in Python, specifically when using a mutable object like a list as a default parameter value.
Step-by-step Explanation:
1. Default Argument Evaluation:
In Python, default arguments are evaluated only once when the function definition is executed, not each time the function is called. This means that if we use a mutable object like a list (lst=[]) as a default argument, the same list object is shared across all function calls that do not provide an explicit argument for that parameter.
2. First Call: print(append_to_lst(1))
Since no list is explicitly passed for the second parameter, Python uses the default list created during function definition.
The number 1 is appended to this default list, making it [1].
The function returns this list, and the code prints:
[1]
3. Second Call: print(append_to_lst(2))
Again, no list is explicitly passed. Python uses the exact same default list object, which currently contains [1].
The number 2 is appended to this shared list, modifying its content to [1, 2].
The function returns this list, and the code prints:
[1, 2]
4. Third Call: print(append_to_lst(3, []))
In this call, a new, empty list [] is explicitly provided as the second argument (lst).
Since an explicit argument is provided, Python does not use the default list.
The number 3 is appended to this newly created list, resulting in [3].
The function returns this new list, and the code prints:
[3]
Combining the outputs of all three calls, we get:
[1]
[1, 2]
[3]
Access expert-curated educational resources and study materials—completely free.
Create, conduct, and manage professional online assessments with Mindyard. Perfect for teachers and institutes.
Copyright © 2026 Mindyard. All Rights Reserved.