title: Is there a Pythonic way to close over a loop variable?
body: <p>I just ran across Eric Lippert's <a href="https://docs.microsoft.com/en-us/archive/blogs/ericlippert/closing-over-the-loop-variable-considered-harmful" rel="noreferrer">Closing over the loop variable considered harmful</a> via SO, and, after experimenting, realized that the same problem exists (and is even harder to get around) in Python.</p>
  
  <pre><code>&gt;&gt;&gt; l = []
  &gt;&gt;&gt; for r in range(10):
  ...   def foo():
  ...      return r
  ...   l.append(foo)
  ...
  &gt;&gt;&gt; for f in l:
  ...   f()
  ...
  9
  9
  9
  # etc
  </code></pre>
  
  <p>and, the standard C# workaround doesn't work (I assume because of the nature of references in Python)</p>
  
  <pre><code>&gt;&gt;&gt; l = []
  &gt;&gt;&gt; for r in range(10):
  ...   r2 = r
  ...   def foo():
  ...      return r2
  ...   l.append(foo)
  ...
  &gt;&gt;&gt; for f in l:
  ...   f()
  ...
  9
  9
  9
  # etc
  </code></pre>
  
  <p>I recognize that this isn't much of a problem in Python with its general emphasis on non-closure object structures, but I'm curious if there is an obvious Pythonic way to handle this, or do we have to go the JS route of nested function calls to create actually new vars?</p>
  
  <pre><code>&gt;&gt;&gt; l = []
  &gt;&gt;&gt; for r in range(10):
  ...     l.append((lambda x: lambda: x)(r))
  ...
  &gt;&gt;&gt; for f in l:
  ...     f()
  ...
  0
  1
  2
  # etc
  </code></pre>