is it because of the reference? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

is it because of the reference?

def cm(): return [ lambda x: i * x for i in range(3)] for m in cm(): print(m(1), end='') output: 222 by: @dash0

5th May 2017, 10:16 AM
Gytree
Gytree - avatar
4 Answers
+ 6
Well, I thought I wa going to lose a few neurons by trying to explain, but making mistake in my logical :P However, I'll get it! :P The cm() function return an array ( list ) containing three annonymized function items ( using list comprehension ), taking a parameter 'x'... so the array contains three functions without name equivalent to: def noname1(x): return i*x def noname2(x): return i*x def noname3(x): return i*x The trap is here, in the value used for 'i' variable: At definition function time, the variable IS NOT replaced by its value, as we can easily missinterpret, but at run-time, so the loop inside the comprehensive list definition is already done and'i' remained with its last value: always 2 for each annonymized function ^^ So, each three function are equivalent to: def noname(x): return 2*x ... and so we'll get an array equivalent to: a = [ noname1, noname2, noname3 ] ... or simpliest: a = [ noname, noname, noname ] ... and your loop will look as: for m in a: print(m(1), end='') ... now, you can now better see/understand what happened: The three ( same ) functions are successively called, or the unique is called three times, with same parameter, and so returning same value ( 2 ) three time... The print() function provide the 'end' named parameter wich set an empty string for the output ending ( disabling the default new line char ), producing a one line without space three "2" output: "222" ;)
5th May 2017, 9:22 PM
visph
visph - avatar
+ 5
As this, this code doesn't output 222 but throw an undefined global variable 'i' error ^^
5th May 2017, 3:34 PM
visph
visph - avatar
+ 3
Good explanation, I had already understood with the help of the interpreter, but it is a good explanation, your dead neurons were not wasted. thx
5th May 2017, 9:40 PM
Gytree
Gytree - avatar
+ 2
my bad, wrong typing. edited
5th May 2017, 6:23 PM
Gytree
Gytree - avatar