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

Answers that fall short

Who gets asked this

More Backend Languages questions