1

Preamble

If I have a recursive function in python such as:

def foo(dict_, key, i=0, list_=[]): 
    """
    Iterates through items in a list in a dictionary and returns them.

    Inputs:
         * dict_ <dict> => The dict that stores the data
         * key <*> => The key to be iterated over.
    """
    if i == len(dict_[key]): return list_ 
    else:  
        list_.append(dict_[key][i]) 
        return foo(dict_, key, i+1, list_) 

Here if I call this function once as below:

bar = {'a': [1, 2, 3], 'b': [4, 5, 6]}
foo(bar, 'a')

the list [1, 2, 3] is returned as expected.

However, if I call the function twice as:

bar = {'a': [1, 2, 3], 'b': [4, 5, 6]}
foo(bar, 'a')
foo(bar, 'b')

the list [1, 2, 3, 4, 5, 6] is returned.


Question

Where is the list_ argument in the stored and why is it not created as a new empty list for each function call?



N.B

If anyone else has come across this and are quite annoyed/confused at this behaviour I found the following trick to get around it:

def foo(dict_, key, i=0, list_=[]): 
    """
    Iterates through items in a list in a dictionary and returns them.

    Inputs:
         * dict_ <dict> => The dict that stores the data
         * key <*> => The key to be iterated over.
    """
    if list_ is False: list_ = []

    if i == len(dict_[key]): return list_ 
    else:  
        list_.append(dict_[key][i]) 
        return foo(dict_, key, i+1, list_) 
Matt Ellis
  • 142
  • 9

0 Answers0