strange overwriting occurring when using lambda functions as dict values

Question:

I’m trying to create a dict containing several lambda functions. The lambda functions are numpy percentile functions. However I get strange results, as if all lambda functions contain np.percentile(x,q=100).

import numpy as np

d = {}
inc = 10

for i in range(0,101,inc):
    d[str(i)+'_perc'] = lambda x: np.percentile(x,q=i)

a = [1,2,3,4,5]

print(d)
print(d['10_perc'](a))
print(d['50_perc'](a))
print(d['90_perc'](a))

Printing produces:

{'50_perc': <function <lambda> at 0x2cb7b90>, '70_perc': <function <lambda> at 0x2cb77d0>, '40_perc': <function <lambda> at 0x2cb75f0>, '10_perc': <function <lambda> at 0x2cb7cf8>, '30_perc': <function <lambda> at 0x2cb7500>, '0_perc': <function <lambda> at 0x2cb7aa0>, '80_perc': <function <lambda> at 0x2cb78c0>, '20_perc': <function <lambda> at 0x2cb7a28>, '100_perc': <function <lambda> at 0x2cb7848>, '90_perc': <function <lambda> at 0x2cb7758>, '60_perc': <function <lambda> at 0x2cb7d70>}
5
5
5

As if all lambda functions were overwritten by the subsequent function…

Asked By: user3439329

||

Answers:

Found a solution:

Something with late bindings that I don’t quite understand. Anyways

def returnLambda(i):
    return lambda x: np.percentile(x,i)

for i in xrange(0,101,10): 
    d[str(i)+'_perc'] = returnLambda(i)
    print(i)
Answered By: user3439329
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.