Why does this code print “d, d, d, d”, and not “a, b, c, d”? How can I modify it to print “a, b, c, d”?
cons = []
for i in ['a', 'b', 'c', 'd']:
cons.append(lambda: i)
print ', '.join([fn() for fn in cons])
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Oddly enough, this is not a variable scope problem, but a quesiton of the semantics of python’s
forloop (and of python’s variables).As you expect,
iinside your lambda correctly refers to the variableiin the nearest enclosing scope. So far, so good.However, you are expecting this to mean the following happens:
What actually happens is this:
Thus, your code is appending the same variable
ito the list four times — and by the time the loop exits,ihas a value of'd'.Note that if python functions took and returned the value of their arguments / return values by value, you would not notice this, as the contents of
iwould be copied on each call toappend(or, for that matter, on each return from the anonymous function created withlambda). In actuality, however, python variables are always references to a particular object– and thus your four copies ofiall refer to'd'by then end of your loop.