by gejjaxxita · 12y ago · 0 comments
Programming languages are meant to be read as well as written, and someone relatively new to Python (and many who have used the language for a long time) is certain to get confused about the difference between:
return [lambda x, i=i : i * x for i in range(5)]
and return [lambda x : i * x for i in range(5)]Being more explicit and less hacky can well be combined with staying true to functional style:
from functools import partial
mul = lambda x, y: x*y # could use int.__mul__, too
multipliers = [partial(mul, n) for n in range(5)]
It does the closure-capturing of n for you.It would have a big ugly 'return' in it and be a few characters longer, but it would work the same, so I don't see what lambda brings to it.