Issue calling lambda stored in dictionary

Question:

I’m currently learning Python and playing with the concepts of dictionaries and lambda functions. I have an issue with the following code:

def helloName(name):
    print 'hello %s' % name

myList = ['one', 'two', 'three']
myDict = {}

print '====' * 4

for i in myList:
    myDict[i] = lambda: helloName(i)
    print i + ' : ' +  str(myDict[i])

print '====' * 4

myDict['one']()
print myDict['one']
myDict['two']()
print myDict['two']
myDict['three']()
print myDict['three']

print '====' * 4

for i in myList:
    myDict[i]()
    print i + ' : ' +  str(myDict[i])

The output of this script is:

================
one : <function <lambda> at 0x0060C330>
two : <function <lambda> at 0x01FB4FB0>
three : <function <lambda> at 0x01FA9570>
================
hello three
<function <lambda> at 0x0060C330>
hello three
<function <lambda> at 0x01FB4FB0>
hello three
<function <lambda> at 0x01FA9570>
================
hello one
one : <function <lambda> at 0x0060C330>
hello two
two : <function <lambda> at 0x01FB4FB0>
hello three
three : <function <lambda> at 0x01FA9570>

I don’t understant the second block of outputed lines. I expected exactly the same output as the third block of outputed lines.

Could you help me understanding the difference between both outputs and suggest a modification to have twice the same output?

Asked By: Grimmy

||

Answers:

It is because of the closure property of Python. To fix this

myDict[i] = lambda i=i: helloName(i)

This question has been answered already here, here, here, here and here

Answered By: thefourtheye