Where Are Lambda Functions Useful?
Lambda functions in Python tend to be the subject of controversy. Here are some of the reasons that lambda functions in Python can be controversial:
- Issues with readability
- The imposition of a functional way of thinking
- Heavy syntax with the
lambda
keyword
Despite the heated debates questioning the very existence of this feature in Python, lambda functions have properties that sometimes provide value to the Python language and to developers.
00:00 Where are lambda functions useful?
00:05 Lambda functions are useful as small, throwaway single-line functions.
00:10 A good analogy is that they’re similar to the kind of jigs that woodworkers and metalworkers make when they have repeated tasks to do. They may create something that allows them to define an angle or a length repeatedly without measuring, but at the end of the day when the job is finished, that will get thrown away.
00:27
They’re often useful to allow quick calculations or processing as the input to other functions. They can make code easier to read if and only if they’re used appropriately. Let’s look at appropriate use now. On the left of the screen, you can see that a second()
function has been created, which returns the second element of a list or tuple which is passed to it.
00:53
Then a list has been created and the .sort()
method is then sorting a
using the second()
function to allow it to access the second of each tuple which is contained inside the list. While this is readable, you have to look elsewhere to find the second()
function and understand what’s going on. Now let’s look at the lambda form of the same code. You can see we have the same list of tuples defined, but then the .sort()
method is using a lambda expression for key
, where the lambda expression is returning the second element of each tuple which is passed to it, and that is used as the key
for sorting.
Become a Member to join the conversation.