Monday, 13 July 2026

Python Question: ID-PY28302

The Classic Python Bug: Do You Know Your Default Arguments?

The Classic Python Bug: Do You Know Your Default Arguments?

Here is a tricky bug that almost every Python developer has written at least once in their career. It tests an intermediate concept that is crucial for writing clean, bug-free code—especially when you start dealing with complex data pipelines or web frameworks.

Take a look at the function below. Without running the code in your IDE, try to figure out what the exact output of the three print statements will be.

The Challenge

def add_employee(name, team=[]):
    team.append(name)
    return team

# Let's hire some folks!
dev_team = add_employee("Alice")
design_team = add_employee("Bob", [])
marketing_team = add_employee("Charlie")

# What gets printed?
print(f"Devs: {dev_team}")
print(f"Design: {design_team}")
print(f"Marketing: {marketing_team}")

Do you have your answer? Drop your guess in the comments below before you check the solution! Bonus points if you can explain exactly why it behaves this way.

Click here to reveal the output and explanation

The Output:

Devs: ['Alice', 'Charlie']
Design: ['Bob']
Marketing: ['Alice', 'Charlie']

Why does this happen?

In Python, default arguments are evaluated only once at the time the function is defined, not every time the function is called.

  • Because team=[] is a mutable object (a list), that exact same list in memory is reused for every function call that doesn't explicitly provide a second argument.
  • Alice is added to this default list.
  • Bob gets his own isolated team because we explicitly passed in a brand new, empty list [] during his function call.
  • Charlie is passed without a second argument, so Python uses the default list again—which already has Alice sitting inside it!

The Fix: Always use None for mutable default arguments!

def add_employee(name, team=None):
    if team is None:
        team = []
    team.append(name)
    return team

Did you get it right? Let me know in the comments below!

1 comment:

  1. Design and marketing teams output are correct but developer teams output is wrong

    ReplyDelete