Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluating a list of python lambda functions only evaluates the last list element

Tags:

python

I have a list of lambda functions I want to evaluate in order. I'm not sure why, but only the last function gets evaluated. Example below:

  >>> def f(x,z):
  ...     print "x=",x,", z=",z
  ... 
  >>> 
  >>> g = lambda x : f(x,13)
  >>> g(2)
  x= 2 , z= 13    # As expected
  >>> 
  >>> lst=[]
  >>> 
  >>> for i in range(0,5): 
  ...    lst.append(lambda x: f(x,i))
  ... 
  >>> print lst
  [<function <lambda> at 0x10341e2a8>, <function <lambda> at 0x10341e398>, <function <lambda> at 0x10341e410>, <function <lambda> at 0x10341e488>, <function <lambda> at 0x10341e500>]
  >>> 
  >>> for fn in lst:
  ...   fn(3)
  ... 
  x= 3 , z= 4 # z should be 0
  x= 3 , z= 4 # z should be 1
  x= 3 , z= 4 # z should be 2
  x= 3 , z= 4 # z should be 3
  x= 3 , z= 4 # as expected.

I think only the last one is getting executed, but not the others. Any ideas? Thanks!

like image 308
Nawal Avatar asked May 19 '11 13:05

Nawal


1 Answers

The lambda is just looking up the global value of 'i'.

Try the following instead:

for i in range(0,5):
  lst.append(lambda x, z=i: f(x,z))
like image 68
bluepnume Avatar answered Sep 27 '22 21:09

bluepnume