Search code examples
pythonconstantslambda

constant lambda function in python


How shall I define a constant lambda function in python?

I need it to evaluation expressions like

lam (array[1,2,3,4,5])

For now I used

lam = lambda t: 1 + t*0 

It works but is it too wasteful?


Solution

  • if you just want to have a function that returns the same thing, no matter what arguments it's called with, That's A-OK! You are not in any way obligated to use any of your arguments.

    In python, lambda is a function without a name (and some other, unrelated limitations)

    If you are going to take the lambda expression and immediately assign its return value to a variable, you are giving a function a name. Don't do that, just define a regular function. You should reach for lambda when you need to pass a function to another function, and the function you want to use is little, and doesn't even merit a name (like when it always returns 1). Python has a few such "high order functions" (functions that take other functions as arguments), map, filter and reduce are in the built in namespace.

    #never!
    always_return_one = lambda ignored_argument: 1
    
    #OK: functions with names are def'ed not lambda'd
    def always_return_one(ignored_argument):
        return 1
    
    #Also OK: pass the lambda to another function as soon as you spell it.
    modified_list = some_highorder_function(lambda ignored: 1, [1, 2, 3, 4, 5])
    

    Some of the most used high order functions in python have a special syntax. In the case above, if the function was map, you can use a list comprehension like so:

    modified_list = [1 for ignored in [1, 2, 3, 4, 5]]
    

    which reads a little easier and is consistently faster!