title: Python - using a shared variable in a recursive function
body: <p>I'm using a recursive function to sort a list in Python, and I want to keep track of the number of sorts/merges as the function continues. However, when I declare/initialize the variable inside the function, it becomes a local variable inside each successive call of the function. If I declare the variable outside the function, the function thinks it doesn't exist (i.e. has no access to it). How can I share this value across different calls of the function?</p>
  
  <p>I tried to use the "global" variable tag inside and outside the function like this:</p>
  
  <pre><code>global invcount  ## I tried here, with and without the global tag
  
  def inv_sort (listIn):
      global invcount   ## and here, with and without the global tag
  
      if (invcount == undefined):  ## can't figure this part out
          invcount = 0
  
      #do stuff
  </code></pre>
  
  <p>But I cannot figure out how to check for the undefined status of the global variable and give it a value on the first recursion call (because on all successive recursions it should have a value and be defined).</p>
  
  <p>My first thought was to return the variable out of each call of the function, but I can't figure out how to pass two objects out of the function, and I already have to pass the list out for the recursion sort to work. My second attempt to resolve this issue involved me adding the variable <code>invcount</code> to the list I'm passing as the last element with an identifier, like <code>"i27"</code>. Then I could just check for the presence of the identifier (the letter <code>i</code> in this example) in the last element and if present pop() it off at the beginning of the function call and re-add it during the recursion. In practice this is becoming really convoluted and while it may work eventually, I'm wondering if there is a more practical or easier solution.</p>
  
  <p>Is there a way to share a variable without directly passing/returning it?</p>