What will be the output of the following Python code and why?
💡 Model Answer
The code defines a function append_item with a default argument lst=[]. In Python, default arguments are evaluated only once when the function is defined, not each time it is called. Therefore, the same list object is reused across calls. The first call append_item(1) appends 1 to the default list and returns [1]. The second call append_item(2) appends 2 to the same list, resulting in [1, 2]. Thus the printed output is:
[1]
[1, 2]This demonstrates the pitfall of using mutable objects as default arguments. The recommended practice is to use None as the default and create a new list inside the function: def append_item(item, lst=None): lst = [] if lst is None else lst.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers — invisible to screen sharing.
Get Assisting AI — Starts at ₹500