Demystifying Python Lambda Functions
With the introduction of ES6, JavaScript has the infamous and powerful inline/anonymous function syntax, which reduced code complexity greatly.
Now with this out of the way, can we do the same thing with Python? How can we write inline functions without having to explicitly define one? You can do it using lambda functions.
Lambda Function Syntax
Lambda functions put simple are small and anonymous functions. Like a regular function, it can take any number of arguments, but can only return one expression.
lambda functionArguments : expression
Where would you use lambda functions in your code?
We can easily recreate the previous JavaScript code, which took an array of numbers and created a new array with the numbers squared, as follows:
As you can see, the lambda function implementation was much cleaner and took less lines of code compared to the explicit function implementation. Some may argue that lambda functions will result in hairy one liners, but I think the benefits outweigh the risks.
Here is another use case where lambda functions greatly reduce code size and complexity:
Where you should NOT use lambda functions
Although lambda functions are great, overusing them may result in hairy code that some formatters may not be able to format properly, so be aware not to overuse it.
How does it compare to JavaScript’s Anonymous Functions?
If I’m being honest, if we compare JS’s arrow functions to Python’s lambda functions, arrow functions would be a complete winner.
One of the main reasons is that arrow functions can not only be shortened into anonymous functions, but they can be used in place of regular functions, so there is over usage issue.
In General
Python Lambda functions are a great way to clean up your code. Nice clean implementations can lead to better looking code, and it also makes sure that you can look at it in a couple years and actually understand it 😅. Make sure to not overuse it though!
Thanks for reading till the end 😊. Signing Off.
Feel free to reach out to me through my GitHub or email me at rayan.quack.you@gmail.com