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>This code is not "simple", it's actually somewhat tricky to understand for a Python novice.</p>

<p>The <code>for key in dict:</code> simply loops over what <code>dict</code> is. Normally <code>dict</code> is a predefined system library class (the class of standard dictionaries) and iterating over a class object is (normally) nonsense.</p>

<p>Python however allows to redefine what <code>dict</code> is bound to: <code>dict</code> is not a keyword, but just a regular name that can be reused as you like - if you like to write bad python code that confuses IDEs and fellow programmers.</p>

<p>I'll assume that <code>dict</code> in this context is some kind of container that can be iterated over: it could be a list, a tuple or a dictionary (as the name suggests) for example. Note that iterating over a dictionary means in Python iterating over dictionary keys.</p>

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

<p>this code creates an unnamed function that accepts a parameter named <code>key</code>, and defines the default value to be current value of variable <code>key</code> used in the loop. The body of the function simply calls the standard <code>print</code> function passing <code>key</code> as argument.</p>

<p>The code is equivalent to:</p>

<pre><code>f = lambda x=key: print(x)
</code></pre>

<p>that is probably a bit clearer for a novice because avoids reusing the same name.</p>

<p>Finally at each iteration this function is called passing no parameters and the result is sent to <code>print</code> standard function. The evaluation of <code>f()</code> will print the <code>key</code> value (passing no parameters the default value will be used) and the result of <code>print</code> (that is <code>None</code>) will be printed by the second <code>print</code> call.</p>

<p>There is really nothing good about this example. Actually the <code>lambda x=x:...</code> is a pattern in Python and sometimes is necessary but here is complete nonsense and there's nothing to learn from this use.</p>

<p>You should reconsider continuing reading from the source you got this from (I'd suspect that the rest is bad stuff also). Stick to official tutorials for better examples...</p>

python