All jobs / Backend developer / Backend Languages
Backend developer interview question · 0–1 years
def add(item, bag=[]): bag.append(item); return bag — you call add(1) then add(2). What comes back the second time?
The strongest answer
[1, 2] — the default list is created once when the function is defined, so every call without a bag shares it; use bag=None and build a new list inside
Why it works
Exactly. One default object, shared for the life of the function. None plus a fresh list inside is the fix.
What a good answer covers
- Default arguments are evaluated once, at definition.
- A mutable default is shared by every call.
- Use None and create the value inside the function.
- The bug is silent, not an error.
Answers that fall short
- Close, but not the strongest: [2], because each call starts with a fresh empty list
That is what most people expect, and why this bug is so common. The default is evaluated once, not per call. - Weak: It raises an error on the second call
It does not raise — it quietly accumulates, which is what makes it dangerous. - Red flag: It depends on the Python version
It has behaved this way in every version; it is the language, not a quirk.
Who gets asked this
- Backend developer
- Full-stack developer
- Automation developer
- DevOps / SRE / cloud
- Data analyst / BI
- Data engineer
- Data science / ML / AI
- AI engineer
More Backend Languages questions
- You pass a class instance and a struct to a method and both are modified inside. What does the caller see?
- When would you choose a tuple over a list?
- What is the most common cause of a NullReferenceException in a new codebase?
- What is the difference between == and is?
- When do you use an array rather than a List<T>?
- You want a value from a dict, or a default if the key is missing, without raising. What do you use?
- You remove items from a List<T> inside a foreach over it and get an exception. Why?
- if items: — what exactly is being tested?