Python - Function Lambda

Introduction

Python provides an expression form that generates function objects, which is called lambda.

Lambdas are sometimes known as anonymous functions.

They are often used as a way to inline a function definition, or to defer execution of a piece of code.

The lambda's general form is the keyword lambda, followed by one or more arguments followed by an expression after a colon:

lambda argument1, argument2,... argumentN : expression using arguments 

lambda is an expression, not a statement.

A lambda can appear inside a list literal or a function call's arguments, for example.

With def, functions can be referenced by name but must be created elsewhere.

As an expression, lambda returns a value that can optionally be assigned a name.

The def statement always assigns the new function to the name in the header.

Lambda's body is a single expression, not a block of statements.

For the following code

Demo

def func(x, y, z): return x + y + z 

print( func(2, 3, 4) )

Result

You can achieve the same effect with a lambda expression by explicitly assigning its result to a name through which you can later call the function:

Demo

f = lambda x, y, z: x + y + z 
print( f(2, 3, 4) )

Result

Here, f is assigned the function object the lambda expression creates; this is how def works, too, but its assignment is automatic.

Related Topics