- Learn Python by Building Data Science Applications
- Philipp Kats David Katz
- 189字
- 2021-06-24 13:06:04
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.
After learning about anonymous functions and how they work, let's move on to what recursion means for a function.