title: The output of [lambda x:i*x for i in range(4)]
body: <p>I encountered such an interview question : </p>
  
  <blockquote>
    <p>Tell the output of the following snippet:</p>
  </blockquote>
  
  <pre><code>def num():
      return [lambda x:i*x for i in range(4)]
  print([m(2)for m in num()])
  </code></pre>
  
  <p>I thought it simple and guessed <code>[0, 2, 4, 6]</code></p>
  
  <p>Unfortunately </p>
  
  <pre><code>In [1]: def num():
     ...:     return [lambda x:i*x for i in range(4)]
  
  In [2]: print([m(2) for m in num()])
  [6, 6, 6, 6]
  </code></pre>
  
  <p>Review its details</p>
  
  <pre><code>In [5]: for _ in num():
     ...:     print(_)
     ...: 
  &lt;function num.&lt;locals&gt;.&lt;listcomp&gt;.&lt;lambda&gt; at 0x7f042411dc80&gt;
  &lt;function num.&lt;locals&gt;.&lt;listcomp&gt;.&lt;lambda&gt; at 0x7f0424182378&gt;
  &lt;function num.&lt;locals&gt;.&lt;listcomp&gt;.&lt;lambda&gt; at 0x7f04240dfc80&gt;
  &lt;function num.&lt;locals&gt;.&lt;listcomp&gt;.&lt;lambda&gt; at 0x7f042410ed08&gt;
  </code></pre>
  
  <p>What's the name of such an obscure grammar to define a num,<br>
  How could it output such a rusult as <code>[6, 6, 6,6]</code></p>
  
  <p>I read the <a href="https://stackoverflow.com/questions/10070477/lambdas-inside-list-comprehensions">python - Lambdas inside list comprehensions - Stack Overflow</a></p>
  
  <pre><code>&gt;&gt;&gt; y = 3
  &gt;&gt;&gt; f = lambda: y
  &gt;&gt;&gt; f()
  3
  &gt;&gt;&gt; y = 4
  &gt;&gt;&gt; f()
  4
  </code></pre>
  
  <p>Put it in a standard way </p>
  
  <pre><code>In [15]: def foo(): return x
  
  In [16]: x = 1; foo()
  Out[16]: 1
  
  In [17]: x = 4; foo()
  Out[17]: 4
  </code></pre>
  
  <p>The explanation is not conceivable which does not illustrate closure.</p>
  
  <p>the wikipedia's answer is better to take it as an obscure usage of closure to shadow vaiable</p>
  
  <blockquote>
    <p>This can also be achieved by variable shadowing (which reduces the scope of the non-local variable), though this is less common in practice, as it is less useful and shadowing is discouraged. In this example f can be seen to be a closure because x in the body of f is bound to the x in the global namespace, not the x local to g:</p>
  </blockquote>
  
  <p><a href="https://en.wikipedia.org/wiki/Closure_(computer_programming)" rel="nofollow noreferrer">Closure (computer programming) - Wikipedia</a></p>
  
  <pre><code>x = 0
  
  def f(y):
      return x + y
  
  def g(z):
      x = 1  # local x shadows global x
      return f(z)
  
  g(1)  # evaluates to 1, not 2
  </code></pre>