Home > Articles > Python Puzzlers

Python Puzzlers

Default arguments

What is the output of this code?

def foo(arg=[]):
    return arg

my_list = foo()
my_list.extend('abc')

print(foo())

My first intution was that this would output the empty list ([]). However, the output is:

['a', 'b', 'c']

Why does this happen? Well, Python evaluates default arguments when the function is defined, rather than when it's run. As a consequence, if a default argument is mutable and is mutated in one function call, future function calls will be working with the mutated argument.

Check your understanding

Now that you know a bit more about default arguments, what is the output of this code?

def bar(arg=[]):
    arg.append('a')
    return arg

bar()
print(bar())

If you answered:

['a', 'a']

then you're right!