title: Persistent arguments in recursive function between function calls
body: <h1>Preamble</h1>
  
  <p>If I have a recursive function in python such as:</p>
  
  <pre><code>def foo(dict_, key, i=0, list_=[]): 
      """
      Iterates through items in a list in a dictionary and returns them.
  
      Inputs:
           * dict_ &lt;dict&gt; =&gt; The dict that stores the data
           * key &lt;*&gt; =&gt; 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_) 
  </code></pre>
  
  <p>Here if I call this function once as below:</p>
  
  <pre><code>bar = {'a': [1, 2, 3], 'b': [4, 5, 6]}
  foo(bar, 'a')
  </code></pre>
  
  <p>the list <code>[1, 2, 3]</code> is returned as expected.</p>
  
  <p>However, if I call the function twice as:</p>
  
  <pre><code>bar = {'a': [1, 2, 3], 'b': [4, 5, 6]}
  foo(bar, 'a')
  foo(bar, 'b')
  </code></pre>
  
  <p>the list <code>[1, 2, 3, 4, 5, 6]</code> is returned.</p>
  
  <p><br></p>
  
  <h1>Question</h1>
  
  <p>Where is the list_ argument in the stored and why is it not created as a new empty list for each function call?</p>
  
  <p><br>
  <hr></p>
  
  <h3>N.B</h3>
  
  <p>If anyone else has come across this and are quite annoyed/confused at this behaviour I found the following trick to get around it:</p>
  
  <pre><code>def foo(dict_, key, i=0, list_=[]): 
      """
      Iterates through items in a list in a dictionary and returns them.
  
      Inputs:
           * dict_ &lt;dict&gt; =&gt; The dict that stores the data
           * key &lt;*&gt; =&gt; 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_) 
  </code></pre>