Understanding anonymous (lambda) functions

In some cases, it is convenient to declare simple one-time functions in place; for that, we can use lambdas – anonymous functions (they are anonymous in the sense that you won't store them in-memory, so there is no name for them). Lambdas use simplified syntax:

lambda <arguments>: <code> 

Note that there is no return keyword – lambda will return the result of the code automatically. It also does not accept multiline code.

Take a look at this example:

models = [
‘Bimbus-3000',
‘Nimbus-1000',
‘Timbus-2000'
]

sort(models, key=lambda x: x[-4:])

The output for the preceding code would be as follows:

>>> [‘Nimbus-1000',‘Timbus-2000', ‘Bimbus-3000']

Here, the array of strings are sorted – however, the string's alphanumeric order is only applied to the last four characters, as we use lambda to return them as keys.

Technically, you can store lambda to a variable, and then use it as a regular function. Don't do it! This is really bad practice.

After learning about anonymous functions and how they work, let's move on to what recursion means for a function.

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

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