title: Python recursive call inside a loop. How does it work?
body: <p>I came across a loop with a recursive function call inside, where the start range of loop is incremented as follows. The code outputs the following sequence as below. However, I unable to conceptualize why this particular sequence is generated. Can somebody throw some insight into its working. And how feasible is it to convert this recursive function into an iterative function outputting the same sequence. Please help.</p>
  
  <p><strong>Code:</strong></p>
  
  <pre><code>def foo(step=0):
      for i in range(step, 4):
          print step
          foo(step+1)
  
  foo()   
  </code></pre>
  
  <p><strong>Output:</strong></p>
  
  <blockquote>
    <p>0 1 2 3 2 3 1 2 3 2 3 1 2 3 2 3 0 1 2 3 2 3 1 2 3 2 3 1 2 3 2 3 0 1 2
    3 2 3 1 2 3 2 3 1 2 3 2 3 0 1 2 3 2 3 1 2 3 2 3 1 2 3 2 3</p>
  </blockquote>
  
  <p><strong>Code of similar design to find Anagrams:</strong></p>
  
  <pre><code>def find_anagrams(word, step=0):
      print 'step-&gt;', step
      if step == len(word):
          print "".join(word)
      for i in range(step, len(word)):
          print step, i
          word_ = list(word)
          word_[step], word_[i] = word_[i], word_[step]
          find_anagrams(word_, step+1)
  </code></pre>