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])
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])
Oddly enough, this is not a variable scope problem, but a quesiton of the semantics of python's for loop (and of python's variables).
As you expect, i inside your lambda correctly refers to the variable i in the nearest enclosing scope. So far, so good.
However, you are expecting this to mean the following happens:
for each value in the list ['a', 'b', 'c', 'd']:
instantiate a new variable, i, pointing to the current list member
instantiate a new anonymous function, which returns i
append this function to cons
What actually happens is this:
instantiate a new variable i
for each value in the list ['a', 'b', 'c', 'd']:
make i refer to the current list member
instantiate a new anonymous function, which returns i
append this function to cons
Thus, your code is appending the same variable i to the list four times -- and by the time the loop exits, i has 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 i would be copied on each call to append (or, for that matter, on each return from the anonymous function created with lambda). In actuality, however, python variables are always references to a particular object-- and thus your four copies of i all refer to 'd' by then end of your loop.
i after exiting the loop. You can also verify that all four lambda functions are technically different functions by printing cons and comparing the ID's.