Sometimes it seems natural to have a default parameter which is an empty list. Yet Python produces unexpected behavior in these situations.

If for example, I have a function:

def my_func(working_list=[]):
    working_list.append("a")
    print(working_list)

The first time it is called, the default will work, but calls after that will update the existing list (with one "a" each call) and print the updated version.

So, what is the Pythonic way to get the behavior I desire (a fresh list on each call)?

9 Answers
9

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *