title: How can I recursively generate lambda functions based on previously generated ones?
body: <p>SOLVED:</p>
  <p>The problem is the references to <code>ii</code> in the lambda, which get looked up by name at the time the function is called. By that time, <code>ii</code> has its final value, equal to n, rather than the proper value for that level of the function. One fix would be to write the function as <code>lambda x, ii=ii:</code> ... to capture <code>ii</code>'s value at the time of definition.</p>
  <p>Thank you @jasonharper</p>
  <hr />
  <p>I am trying to generate a lambda function based on the Hermite series, which is a series of polynomial equations that rely on previous terms to calculate them. I am sure that a closed-form definition exists, but I am required to calculate them recursively. My function should return a lambda function representing the correct polnomial given the value of n. Here is my current attempt:</p>
  <pre><code>def hermite(n):
      functions = [None]*(n+1)
      first = lambda x: x-x+1 # just setting it to 1 causes issues.
      second = lambda x: 2*x
    
      functions[0] = first
      if n == 0:
          return functions[n]
      functions[1] = second 
      if n == 1:
          return functions[n]
  
      for ii in range(2,n+1):
          functions[ii] = lambda x: 2*x*functions[ii-1](x) - 2*(n-1)*functions[ii-2](x)
          
      return functions[n]
  </code></pre>
  <p>I tested it with this code:</p>
  <pre><code>xvals = np.linspace(-3,3,1001)
  f = hermite(2) #changing this number to 3 breaks my code
  yvals = f(xvals)
  plt.plot(xvals,yvals)
  </code></pre>
  <p>I believe that the for loop should recursively genereate lambda functions up to n, and it does generate the n=2 polynomial correctly. However, when I try to generate the n=3 polynomial, I can no longer use it. Why does it break for the <em>second</em> iteration of the for loop, not the first, and how can I fix it?</p>