Anonymous Functions (Lambdas)#

Sometimes one has to call functions which take a function as argument. Passing a function as argument is very simple, just give the function’s name as argument:

def my_function(arg1, arg2):
    # some code
    
some_function(my_function)

Often, functions passed to other functions are needed only once in the code and almost always they have very simple structure. Providing a full function definition and wasting a name for such throwaway functions, thus, should by avoided. The tool for avoiding this overhead are anonymous functions, in Python known as lambdas. Here is an example:

some_function(lambda arg1, arg2: SOME SHORT CODE)

The lambda keyword creates a function in the same way as def, but without assigning a name to it. Keyword arguments are allowed, too. In principle it is possible to define named functions with lambda:

my_function = lambda arg1, arg2: SOME SHORT CODE

But this should be avoided to keep code readable.