meade meade - 6 months ago 31
Python Question

Why are Python lambdas useful?

I'm trying to figure out python lambdas. Is lambda one of those 'interesting' language items that in real life should be forgotten?

I'm sure there are some edge cases where it might be needed, but given the obscurity of it, the potential of it being redefined in future releases (my assumption based on the various definitions of it) and the reduced coding clarity - should it be avoided?

This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values. It feels like sort of a techie showmanship but maintenance coder nightmare.


Are you talking about lambda functions? Like

f = lambda x: x**2 + 2*x - 5

Those things are actually quite useful. Python supports a style of programming called functional programming where you can pass functions to other functions to do stuff. Example:

mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])

sets mult3 to [3, 6, 9], those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than

def filterfunc(x):
    return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])

Of course, in this particular case, you could do the same thing as a list comprehension:

mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]

(or even as range(3,10,3)) but there are other cases, like constructing functions as return values from other functions, where you can't use a list comprehension and a lambda function may be the shortest way to write something out. Like

def transform(n):
    return lambda x: x + n
f = transform(3)
f(4) # is 7

I use lambda functions on a regular basis. It took a while to get used to them but once I did I'm glad Python has them ;-)