Problem Statement
What is the safest way to handle a list default argument in a function?
Explanation
Default arguments are evaluated once at function definition time. A mutable default like a list is shared across calls and can cause subtle bugs.
Using None as the default and creating a new list inside ensures each call gets a fresh object. This is the standard safe pattern interviewers expect.
Code Solution
SolutionRead Only
def add_item(x, arr=None):
if arr is None:
arr = []
arr.append(x)
return arr