Lambdas

An interesting way of making functions is through anonymous functions, also known as lambda expressions. Lambdas create a function that is essentially processed in-line, rather than giving it a name to be called later (hence, the anonymous part). This is useful when the normal def statement wouldn't necessarily work, such as within a list or as a function call's argument.

When using the normal def statement to create a function, the function is assigned a name and called from a different location, possibly multiple times; it also returns an object of some type. When using a lambda, the function itself is the returned object that can be given a name, if desired.

Lambdas look and work differently than regular functions. First, it is a single expression, not a block of code. This is why it can be used in places where a normal function can't; you're essentially creating the return statement directly, rather than calling a function to return a value.

Second, because it's an expression, there's a limit to what it can do. Since expressions break down to a value, whereas statements perform code logic, lambdas are limited in how much work they can do. If you need to do significant work, such as working with if statements or loops, you'll have to create a normally defined function.

Following screenshot provides an example of a normal function versus its equivalent lambda function:

Lambda function

It's somewhat confusing at first, but, as you can see, the lambda is doing the exact same thing that the traditional function does, except it assigns the return value to a variable name automatically, rather than having to be called separately later. The lambda shortcuts the function process in a similar manner as list comprehensions shortcut list creation.

Lambdas work the same as normal functions, with all the features and limitations (actually, a few more limitations, since they only use expressions). Lambdas are a nice feature when you only need quick, inline executable code and a normal function won't work. You'll also find some third-party libraries that require a lambda expression as an argument.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.214.27