title: How are closures implemented?
body: <p>&quot;Learning Python, 4th Ed.&quot; mentions that:</p>
  <blockquote>
  <p>the enclosing scope variable is looked up when the nested functions
  are later called..</p>
  </blockquote>
  <p>However, I thought that when a function exits, all of its local references disappear.</p>
  <pre class="lang-py prettyprint-override"><code>def makeActions():
      acts = []
      for i in range(5): # Tries to remember each i
          acts.append(lambda x: i ** x) # All remember same last i!
      return acts
  </code></pre>
  <p><code>makeActions()[n]</code> is the same for every <code>n</code> because the variable <code>i</code> is somehow looked up at call time. How does Python look up this variable? Shouldn't it not exist at all because <code>makeActions</code> has already exited? Why doesn't Python do what the code intuitively suggests, and define each function by replacing i with its current value within the for loop as the loop is running?</p>