I am never sure which of these is better form:
Option A
def a(x,y):
def b(z): return z+y
return map(b, x)
print a([10,20], 5)
Option B
def b(z,y): return z+y
def a(x,y):
return map(lambda x: b(x,y), x)
print a([10,20], 5)
Suppose that b() is ONLY ever called from inside a().
I know Option B is more efficient because it only declares b() once, and then the variable y is just passed as a context variable. But Option A seems to be simpler syntax, eliminating the need to construct a lambda, and simplifying the interface of b(). Suppose further that there could actually be many context arguments. The complexity blows up on the interface of b():
Option A2:
def a(x,y1,y2,y3,y4,y5):
def b(z): return z+y1+y2+y3+y4+y5
return map(b, x)
print a([10,20], 5,6,7,8,9)
Option B2:
def b(z,y1,y2,y3,y4,y5): return z+y1+y2+y3+y4+y5
def a(x,y1,y2,y3,y4,y5):
return map(lambda x: b(x,y1,y2,y3,y4,y5), x)
print a([10,20], 5,6,7,8,9)
Option A2 is far fewer characters. Thoughts?
b
in your Option Bs doesn't seem to have much point. Why not just domap (lambda x:x+y1+y2+y3+y4+y5, x)
for B2 for instance? In general, I'd only ever use a lambda, or define a function, but never both in conjunction. – Gort the Robot Feb 1 '15 at 22:05