title: Python lambda's binding to local values
body: <p>The following code spits out <code>1</code> twice, but I expect to see <code>0</code> and then <code>1</code>.</p>
  <pre><code>def pv(v) :
    print v
  
  x = []
  for v in range(2):
    x.append(lambda : pv(v))
  
  for xx in x:
    xx()
  </code></pre>
  <p>I expected python lambdas to bind to the reference a local variable is pointing to, behind the scenes. However that does not seem to  be the case. I have encountered this problem in a large system where the lambda is doing modern C++'s equivalent of a bind ('boost::bind' for example) where in such case you would bind to a smart ptr or copy construct a copy for the lambda.</p>
  <p>So, how do I bind a local variable to a lambda function and have it retain the correct reference when used? I'm quite gobsmacked with the behaviour since I would not expect this from a language with a garbage collector.</p>