Creating a list of functions in python (python function closure bug?) -


i understand functional programming well. want create list of functions each selects different element of list. have reduced problem simple example. surely python bug:

fun_list = [] in range(5):     def fun(e):         return e[i]     fun_list.append(fun)  mylist = range(10) print([f(mylist) f in fun_list]) 

"obviously" should return [0,1,2,3,4]. returns [4, 4, 4, 4, 4]. how can coerce python right thing? (hasn't been noticed before? or being thick?)

this python 3.4.0 (default, mar 25 2014, 11:07:05)

thanks, david

how can coerce python right thing?

here 1 approach:

fun_list = [] in range(5):     def fun(e, _ndx=i):         return e[_ndx]     fun_list.append(fun)  mylist = range(10) print([f(mylist) f in fun_list]) 

this works because default value _ndx evaluated , saved when def statement fun executed. (in python, def statements executed.)


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -