0
def mul():
    return [lambda x : i*x for i in range(4)]

when i execute it i get this

[<function __main__.mul.<locals>.<listcomp>.<lambda>>,
<function __main__.mul.<locals>.<listcomp>.<lambda>>,
<function __main__.mul.<locals>.<listcomp>.<lambda>>,
<function __main__.mul.<locals>.<listcomp>.<lambda>>]

and i am using that function as like this

print([f(3) for f in mul()])
[9, 9, 9, 9]

print([f(5) for f in mul()])
[15, 15, 15, 15]

what is happening inside of mul() and inside of print and what here f refers to?

avimatta
  • 119
  • 7
  • 2
    `i` is a closure; it doesn't store the value of `i` when you create the `lambda`, it stores a reference to the same variable, and this variable last referenced `3`. – Martijn Pieters Oct 12 '16 at 12:09
  • @Jérôme: this isn't limited to lambdas, see [Local variables in Python nested functions](//stackoverflow.com/q/12423614) – Martijn Pieters Oct 12 '16 at 12:10

0 Answers0