Python Tip of the Day: Beware of Mutable Default Arguments

Beware of Mutable Default Arguments

Author: Jeremy Morgan
Published: November 5, 2024


Coding with AI

I wrote a book! Check out A Quick Guide to Coding with AI.
Become a super programmer!
Learn how to use Generative AI coding tools as a force multiplier for your career.


Using mutable default arguments like lists can lead to unexpected behavior. Here’s why.

# Function with mutable default argument
def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item(1))  # Output: [1]
print(add_item(2))  # Output: [1, 2] - Wait, what?

“Python Tip of the Day: Beware of Mutable Default Arguments”


The Python Tip of the Day is a daily series published in the month of November. The tips are designed to help you become a better Python programmer. I post tips like this and more every single day on X. Let’s connect!


Coding with AI

I wrote a book! Check out A Quick Guide to Coding with AI.
Become a super programmer!
Learn how to use Generative AI coding tools as a force multiplier for your career.