How can I force Python to create a new variable / new scope inside a loop?
<p>Today I explored a <em>weird</em> behavior of Python. An example:</p>

<pre><code>closures = []
for x in [1, 2, 3]:
    # store `x' in a "new" local variable
    var = x

    # store a closure which returns the value of `var'
    closures.append(lambda: var)

for c in closures:
    print(c())
</code></pre>

<p>The above code prints</p>

<pre><code>3
3
3
</code></pre>

<p>But I want it to print</p>

<pre><code>1
2
3
</code></pre>

<p>I explain this behavior for myself that <code>var</code> is always the same local variable (and python does not create a new one like in other languages). How can I fix the above code, so that each closure will return another value?</p>
