Python Forum

Full Version: What data types can I use for default values?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm working my way through _Teach Yourself Visually Python_ (2022). This example was presented:
def parlay(odds1, odds2, odds3 = None, odds4 = None, odds5 = None):
...
Following the example, a Tip is given about what data types to use for default values: "You can use most data types, including None, as in this example... However, in general, it is best to avoid mutable data types because although they work correctly the first time you call the function, subsequent calls to the function will return the last call assigned to the data type. For example, if you use an empty list as a default value, the first call returns an empty list, as expected, but the next call returns a list containing the values you assigned to the list."

I don't follow. Can someone give an example to illustrate this point and why using a mutable data type as default value might cause problems?

Thank you!
https://docs.python-guide.org/writing/go...-arguments
https://stackoverflow.com/q/1132941/4046632
def spam(start=[]):
    start.append(1)
    print(start)


spam()
spam()
Probably you would expect that each call starts with empty dict and get

Output:
[1] [1]
but what you get is
Output:
[1] [1, 1]
The reason - default arguments are evaluated once - at function definition and because you mutate the list when calling the function, the result (i.e. modified list) from previous calls is preserved and that affects next calls.

To prevent this

def spam(start=None):
    if start is None:
        start=[]
    start.append(1)
    print(start)


spam()
spam()
Output:
[1] [1]
There are specific cases where this behaviour might be desirable and if so it can be used, i.e. there is no problem using mutable default arguments as long as you know what to expect.