This is a series of short 10 minute Python articles helping you to boost your knowledge of Python. I try to post an article each day (no promises), starting from the very basics, going up to more complex idioms. Feel free to contact me on LinkedIn for questions or requests on particular subjects of Python you want to know about.

For new-comers, the lambda function can be somewhat intimidating. I have also avoided the use of these functions for some time as I never understood true use of them. Nowadays, I do see a benefit of the construct but it is rather small. You will come across these functions and therefore, it is good to know what is happening. Lambda functions are also called nameless functions or anonymous functions which describes them much better. A lambda function is an inline definition of a function which does not have a name. Apart from not having a name, what is the difference between a regular function and the lambda function? Practically nothing! Then the next question is: why to use a lambda function when a regular function does the same thing? Indeed, most of the time, a regular function is the way to go. However, sometimes you only need to do an operation once. While you could still use a regular function, an inline function (the lambda function) could be somewhat easier.

The definition of a lambda function is short: it starts with the lambda keyword followed by one or more parameters separated by commas. The steps of the function itself follow after a semicolon. Let’s have a look at an example:

In this example we have a list of expenses. Each expense is a tuple with a name and the costs. While there are other ways (like list comprehensions), we choose to use a map() to select all the costs. Map() expects a function and an iterable. We could now create a regular function that selects the second item of the tuple but we only use it once. This means that a lambda function would be perfect here. The map() executes our function on each tuple and returns a list of all the costs, followed by a sum. Now we have a look at some more examples (disclaimer: not all are useful):

In the example we show that a lambda expression returns a reference to the nameless function. The function is now catched by a variable, it will not be ‘garbage-collected’. This eliminates the benefit of the lambda function, namely a one-time nameless function, which will be disposed after its use. If you add a reference to a lambda function, just write a regular function instead. Regular functions are much more readable. Nevertheless, you could catch the lambda function into a reference, and the variable then acts as a regular function (just don’t do it (-;).

Image for post

#python #data-science #programming #10minutespython #machine-learning

Learning Python 10 minutes a day #21
1.40 GEEK