🌐
GeeksforGeeks
geeksforgeeks.org › python › default-arguments-in-python
Default arguments in Python - GeeksforGeeks
In Python, functions can have default arguments, which are parameters with predefined values.
Published: March 18, 2026
🌐
The Hitchhiker's Guide to Python
docs.python-guide.org › writing › gotchas
Common Gotchas — The Hitchhiker's Guide to Python
A new list is created each time ... successive call. Python’s default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby)....
Discussions

Today I re-learned: Python function default arguments are retained between executions
I had to find this out the hard way :/ P.s. I am a little rusty on python, but if you want a mutable default value (say a list) you can make the default None then inside the function you would reassign the variable if it's None. More on reddit.com
🌐 r/Python
170
391
January 20, 2023
python - "Least Astonishment" and the Mutable Default Argument - Stack Overflow
Doing the binding inside the function ... of default parameters) at function invocation time. The actual behavior is more consistent: everything of that line gets evaluated when that line is executed, meaning at function definition. ... I have not doubt mutable arguments violate least astonishment principle for an average person, and I have seen beginners stepping there, then heroically replacing mailing lists with mailing tuples. Nevertheless mutable arguments are still in line with Python Zen (Pep 20) ... More on stackoverflow.com
🌐 stackoverflow.com
What the default arguments are?
Some sources point out that arguments might be default. But they are not clear in what these arguments are. Sometimes it looks like the default arguments are mismatched with keyword-only parameters or positional and keyw… More on discuss.python.org
🌐 discuss.python.org
8
0
October 3, 2023
Python function with default list argument - Stack Overflow
by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function · Please refer to the StackOverflow Discussion here for a discussion related to mutable arguments within the Python ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
HackerOne
hackerone.com › blog › python-pitfalls-perils-using-lists-and-dicts-default-arguments
Python Pitfalls: The Perils of Using Lists and Dicts as Default Arguments | HackerOne
December 19, 2023 - However, the problem lies with using a list (a mutable type) as a default argument. Python’s default arguments are evaluated only once when the function is defined, not each time the function is called.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Default Parameter Values in Python Functions | note.nkmk.me
May 12, 2025 - Consider a function that uses a list or dictionary as a default parameter and adds elements to it. When the function is called multiple times without providing that argument, elements will be added to the same object repeatedly.
🌐
AlgoMaster
algomaster.io › home › python › default & keyword arguments
Default Arguments | Python | AlgoMaster.io
June 6, 2026 - A default value is set in the function signature with name=value. If the caller passes that argument, the value they pass wins. If they don't, the default is used. The first call omits quantity, so Python uses the default 1. The second call ...
🌐
Reddit
reddit.com › r/python › today i re-learned: python function default arguments are retained between executions
r/Python on Reddit: Today I re-learned: Python function default arguments are retained between executions
January 20, 2023 - For better or worse, Python lets you modify a parameter at runtime which makes for succinct cleanup of arguments: def fn(a = None): a = "hello world" if a is None else a · I want to use a = a or "hello world" but that is fraught with side-effects. ... No. strings are immutables in python. It's perfectly safe to write ... “stick to literals” is not good advice. List and dictionary literals would be problematic as default parameter values since those are mutable types.
🌐
Chelsea Troy
chelseatroy.com › 2022 › 03 › 25 › pythons-sneaky-default-argument-behavior-and-what-to-do-about-it
Python’s Sneaky Default Argument Behavior and What to Do About It
February 7, 2023 - Python evaluates default arguments when it places the definition of the function into the environment. Not when it runs that function. So the default arguments keep the id they had at function definition time. No problem when your defaults are immutable. But a list is mutable.
Top answer
1 of 16
1964

Actually, this is not a design flaw, and it is not because of internals or performance. It comes simply from the fact that functions in Python are first-class objects, and not only a piece of code.

As soon as you think of it this way, then it completely makes sense: a function is an object being evaluated on its definition; default parameters are kind of "member data" and therefore their state may change from one call to the other - exactly as in any other object.

In any case, the Effbot (Fredrik Lundh) has a very nice explanation of the reasons for this behavior in Default Parameter Values in Python. I found it very clear, and I really suggest reading it for a better knowledge of how function objects work.

2 of 16
340

Suppose you have the following code

fruits = ("apples", "bananas", "loganberries")

def eat(food=fruits):
    ...

When I see the declaration of eat, the least astonishing thing is to think that if the first parameter is not given, that it will be equal to the tuple ("apples", "bananas", "loganberries")

However, suppose later on in the code, I do something like

def some_random_function():
    global fruits
    fruits = ("blueberries", "mangos")

then if default parameters were bound at function execution rather than function declaration, I would be astonished (in a very bad way) to discover that fruits had been changed. This would be more astonishing IMO than discovering that your foo function above was mutating the list.

The real problem lies with mutable variables, and all languages have this problem to some extent. Here's a question: suppose in Java I have the following code:

StringBuffer s = new StringBuffer("Hello World!");
Map<StringBuffer,Integer> counts = new HashMap<StringBuffer,Integer>();
counts.put(s, 5);
s.append("!!!!");
System.out.println( counts.get(s) );  // does this work?

Now, does my map use the value of the StringBuffer key when it was placed into the map, or does it store the key by reference? Either way, someone is astonished; either the person who tried to get the object out of the Map using a value identical to the one they put it in with, or the person who can't seem to retrieve their object even though the key they're using is literally the same object that was used to put it into the map (this is actually why Python doesn't allow its mutable built-in data types to be used as dictionary keys).

Your example is a good one of a case where Python newcomers will be surprised and bitten. But I'd argue that if we "fixed" this, then that would only create a different situation where they'd be bitten instead, and that one would be even less intuitive. Moreover, this is always the case when dealing with mutable variables; you always run into cases where someone could intuitively expect one or the opposite behavior depending on what code they're writing.

I personally like Python's current approach: default function arguments are evaluated when the function is defined and that object is always the default. I suppose they could special-case using an empty list, but that kind of special casing would cause even more astonishment, not to mention be backwards incompatible.

Find elsewhere
🌐
Quantifiedcode
docs.quantifiedcode.com › python-anti-patterns › correctness › mutable_default_value_as_argument.html
Using a mutable default value as an argument — Python Anti-Patterns documentation
Passing mutable lists or dictionaries ... uses a list or dictionary as the default argument to a function, the programmer wants the program to create a new list or dictionary every time that the function is called. However, this is not what Python does....
🌐
Python.org
discuss.python.org › python help
What the default arguments are? - Python Help - Discussions on Python.org
October 3, 2023 - Some sources point out that arguments might be default. But they are not clear in what these arguments are. Sometimes it looks like the default arguments are mismatched with keyword-only parameters or positional and keyword parameters. E.g.: def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") greet("Alice") greet("Bob", "Hi") One source even suggests that the value of greeting (i.e. “Hello”) is that default argument.
Top answer
1 of 3
8

Although an answer has been accepted, it is interesting as well as important to understand why this happens, so as to avoid not-so-obvious pitfalls.

An excerpt from the Python documentation for compound statements :

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function

Please refer to the StackOverflow Discussion here for a discussion related to mutable arguments within the Python language. The discussion points to a very interesting and informative article on Effbot - Python Default Values which gives a good explanation of why this behavior is observed and the places where such a behavior is desirable - for e.g. a calculator function that performs very computing-intensive calculations may use a dictionary mutable as a default parameter to store the results of a calculation keyed by the parameters used for the calculation. In such a case, when the client requests for a calculation to be performed, the function can look up the dictionary mutable and return the values if already present, else perform the calculation.

Hopefully, this answer provides an insight into this "astonising" behavior of python and help in designing functions that work correctly and are performant.

2 of 3
7

Don't use mutable as keyword arguments.

def test_func( newList, myList=None ):
    myList = [] if myList is None else myList     
🌐
APXML
apxml.com › courses › python-for-beginners › chapter-5-building-blocks-functions › python-default-arguments
Python Default Argument Values | Optional Parameters
First call (safe): List is now: ['apple'] Second call (safe): List is now: ['banana'] Third call, providing a list (safe): List is now: ['start', 'cherry'] Using None as a placeholder default and creating the mutable object within the function ensures that each call relying on the default gets a fresh instance, avoiding unintended side effects between calls. Default argument values are a feature for making your functions more convenient and adaptable, but remember the distinction between mutable and immutable defaults to avoid common issues. ... Fluent Python: Clear, Concise, and Effective Programming, Luciano Ramalho, 2022 (O'Reilly Media) - Provides in-depth coverage of Pythonic idioms, including a detailed discussion on default argument values, their proper use, and the critical issues associated with mutable default arguments, offering practical solutions.
🌐
Python Morsels
pythonmorsels.com › mutable-default-arguments
Mutable default arguments - Python Morsels
June 10, 2026 - Lists are mutable sequences, and tuples are immutable sequences, and both are iterables, so the list function will accept either one just fine. In Python, default argument values are defined when a function is defined.
🌐
Nikos7am
nikos7am.com › posts › mutable-default-arguments
My Python Blog | Avoid using an empty list as a default argument to a function
June 4, 2018 - A very common error in Python is the use of an empty list as a default argument to a function. This is not the right way to do it and can cause unwanted behavior. See for example below: def append_to_list(element, list_to_append=[]): list_to_append.append(element) return list_to_append >>> ...
🌐
Lei Mao's Log Book
leimao.github.io › blog › Python-Default-Argument-Mutable-Object
Python Mutable Object as Default Argument - Lei Mao's Log Book
March 1, 2021 - This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:” · Therefore, the “correct” of implementing class with List object argument is
🌐
Python Tutorial
pythontutorial.net › home › python basics › python default parameters
Python Default Parameters
October 5, 2020 - To specify default values for parameters, you use the following syntax: def function_name(param1, param2=value2, param3=value3, ...):Copy · In this syntax, you specify default values (value2, value3, …) for each parameter using the assignment operator (=). When you call a function and pass ...
🌐
Medium
medium.com › @nebiyuelias1 › be-careful-when-using-default-arguments-in-python-fd92df94efee
Be careful when using default arguments in Python | by Nebiyu Elias | Medium
December 16, 2021 - If you look at Python’s documentation closely, you will find the following warning: Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. The key point to note here is: default mutable argument.
🌐
Codefinity
codefinity.com › courses › v2 › 21fdd593-69da-43bd-97c6-3f1064d7df6e › 66f76386-8c14-4049-88ec-8839cba55a00 › d1f2ab3f-b430-455e-bf65-3808fe5e7521
Learn Mutable Default Arguments | Mutable Objects and Function Arguments
To avoid this pitfall, you should use None as the default value for arguments that are intended to be mutable objects. Inside the function, you can then check if the argument is None and create a new list or dictionary as needed.
🌐
30 Seconds of Code
30secondsofcode.org › home › mutable default arguments
Watch out for mutable default arguments in Python - 30 seconds of code
February 27, 2022 - So, the second time it's called, the function doesn't start out with an empty list. Instead, the default argument is the list containing the value from the previous call.