Python also provides an expression form that generates function objects. Because of its similarity to a tool in the Lisp language, it’s called lambda. Like def, this expression creates a function to be called later, but it returns the function instead of assigning it to a name.
This is why lambdas are sometimes known as anonymous (i.e., unnamed) functions. In practice, they are often used as a way to inline a function definition, or to defer execution of a piece of code.
- lambda is an expression, not a statement
Because of this, a lambda can appear in places a def is not allowed by Python’s syntax—inside a list literal or a function call’s arguments, for example. As an expression, lambda returns a value (a new function) that can optionally be assigned a name.
In contrast, the def statement always assigns the new function to the name in the header, instead of returning it as a result.
- lambda’s body is a single expression, not a block of statements
The lambda’s body is similar to what you’d put in a def body’s return statement; you simply type the result as a naked expression, instead of explicitly returning it.
Because it is limited to an expression, a lambda is less general than a def you can only squeeze so much logic into a lambda body without using statements such as if. This is by
design, to limit program nesting: lambda is designed for coding simple functions,
and def handles larger tasks.
how to make a function with a def statement:
>>>def func(x, y, z): return x + y + z … >>>func(2, 3, 4) 9
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:
>>>f = lambda x, y, z: x + y + z >>>f(2, 3, 4) 9
Here, f is assigned the function object the lambda expression creates; this is how def
works, too, but its assignment is automatic.
Defaults work on lambda arguments, just like in a def:
>>>x = (lambda a="fee", b="fie", c="foe": a + b + c) >>>x("wee") 'weefiefoe
The code in a lambda body also follows the same scope lookup rules as code inside a
lambda expressions introduce a local scope much like a nested def, which automatically sees names in enclosing functions, the module, and the built-in scope (via the LEGB rule):
>>>def knights(): … title = 'Sir' … action = (lambda x: title + ' ' + x) # Title in enclosing def … return action # Return a function … act = knights() act('robin') 'Sir robin'
If you like this post, don’t forget to share 🙂