awkward lambda function
<p>I cannot find out what <code>key=key</code> does in this simple python code:</p>

<pre><code>for key in dict:
    f = (lambda key=key: print(key))
    print(f())
</code></pre>

<p>In <em>this</em> piece of code, <code>key=key</code> does nothing useful at all. You can just as well write the loop as </p>

<pre><code>for key in [1,2,3]:
    f = lambda: key
    print(f())
</code></pre>

<p>This will print <code>1</code>, <code>2</code>, and <code>3</code>. (Note that -- unrelated to the problem -- I also removed the <code>print</code> from the <code>lambda</code>, instead returning the value directly, because it's redundant and will only make the "outer" <code>print</code> print <code>None</code>, as that's what the function would return with <code>print</code>.)</p>

<p>But what if you do not execute the function right within the loop, but afterwards?</p>

<pre><code>functions = []
for key in [1,2,3]:
    f = lambda: key
    functions.append(f)

for f in functions:
    print(f())
</code></pre>

<p>Now, this will print <code>3</code>, <code>3</code>, and <code>3</code>, as the <code>key</code> variable is evaluated when the function is <em>called</em>, not when it is <em>defined</em>, i.e. after the loop when it has the value <code>3</code>. This can lead to some serious surprises e.g. when <a href="http://stackoverflow.com/q/19837486/1639625">defining callback functions for different buttons in a loop</a>.</p>

<p>Here, using <code>key=key</code> comes into play: This will create a parameter <code>key</code> and assign to it the current value of the <code>key</code> variable in the loop <em>when the function is defined</em> as a default value (hence you do not have to pass a parameter when calling the function). The value of that <code>key</code> paremeter will then stay the same <em>within the scope of the function</em> when the function is called later:</p>

<pre><code>functions = []
for key in [1,2,3]:
    f = lambda key=key: key
    functions.append(f)
</code></pre>

<p>This prints <code>1</code>, <code>2</code>, and <code>3</code>, as would be expected. As others have noted, you can use a different name for the parameter, to make this less confusing, e.g. <code>f = lambda param=key: param</code>.</p>

python