title: Capturing Value instead of Reference in Lambdas
body: <p>I was slightly surprised by this example given by Eli Bendersky (<a href="http://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/" rel="noreferrer">http://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/</a>)</p>
  
  <pre><code>&gt;&gt;&gt; def foo():
  ...     lst = []
  ...     for i in range(4):
  ...         lst.append(lambda: i)
  ...     print([f() for f in lst])
  ...
  &gt;&gt;&gt; foo()
  [3, 3, 3, 3]
  </code></pre>
  
  <p>But when I thought about it, it made some sense — the lambda is capturing a reference to i rather than i's value.</p>
  
  <p>So a way to get around this is the following:</p>
  
  <pre><code>&gt;&gt;&gt; def foo():
  ...     lst = []
  ...     for i in range(4):
  ...         lst.append((lambda a: lambda: a)(i))
  ...     print([f() for f in lst])
  ...
  &gt;&gt;&gt; foo()
  [0, 1, 2, 3]
  </code></pre>
  
  <p>It appears that the reason that this works is that when i is provided to the outer lambda, the outer lambda creates a scope and dereferences i, setting a to i. Then, the inner lambda, which is returned, holds a reference to a.</p>
  
  <p>Is this a correct explanation?</p>