Repaso
EspaƱol
PythonIntermediatePY-02

What does this print?

def add(item, bucket=[]):
    bucket.append(item)
    return bucket

add(1)
print(add(2))

Options

  1. [2]
  2. [1, 2] (Correct option)
  3. TypeError
  4. [[1], [2]]

Answer

[1, 2]

Why

Python creates a default value only ONCE, when the def line runs, not on every call.

Here the default is one single list object. Every call that does not pass bucket reuses that same list: the first call adds 1, the second adds 2 to the same list, so it prints [1, 2].

Fix: use None as the default and create a new list inside the function.

def add(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket

Remember

Never use [], {} or set() as a default argument.

Key terms

Practice this question in Repaso