-1

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?

Thanks

heio fhow
  • 19
  • 3

1 Answers1

0

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.

aaronn
  • 448
  • 1
  • 6
  • 16