title: create dynamic functions keeping state
body: <p>Python beginner question. Say you want to dynamically create a function that keeps some state (in the code below an integer i). Then as the function defined is an object, we could use it later on. In the following code, I add the functions to a list, and each call to <code>print(fn(0))</code> should result in <code>0 1 2 3 4</code>, but instead I get <code>4 4 4 4 4</code> as if only the latest value of <code>i</code> is used.</p>
  
  <pre><code>fns = []
  for i in range(5):
  
      def fn(x):
          return x + i
  
      fns += [fn]
  print(fns)
  
  for fn in fns:
      print(fn(0))
  quit()
  </code></pre>
  
  <p>Is it possible to accomplish in Python what this code tries to do?</p>