when do we initialise a function call within the function vs as an argument?

I have a question about arguments in functions, in particular initialising an array or other data structure within the function call, like the following:

def helper(root, result = []):

My question is, what is the difference between the above vs. doing:

def helper(root): 
    result = []

I can see why this would be necessary if we were to run recursions, i.e. we would need to use the first case in some instances.

But are there any other instances, and am I right in saying it is necessary in some cases for recursion, or can we always use the latter instead?


1 answer

  • answered 2021-05-15 11:05 aaronn

    Python uses pointers for lists, so initializing a list or any other mutable objects in function definition is a bad idea. The best way of doing it is like this:

    def helper(root, result=None):
        if isinstance(result, type(None)):
            result = []

    Now if you only pass one argument to the function, the "result" will be an empty list. If you initiate the list within the function definition, by calling the function multiple times, "result" won't reset and it will keep the values from previous calls.