When to use Lambda function?
What's this?
- I'm studying this book.
- I'm curious about when to use the Lambda function, so I'll investigate the topic.
What I learned
What is lambda function?
In Python, you usually use def to create functions.
But, the lambda function can create a small and anonymous function.
It's basically a syntactic sugar for a normal function.
4. More Control Flow Tools — Python 3.12.1 documentation
How to write it
You can create a one-liner function using the lambda function.
sum_a_b = lambda a, b: a + b print(sum_a_b(1, 3)) # => 4
It is syntactically restricted to a single expression, but you can use an if statement to switch which to return.
return_bigger = lambda a,b: a if a > b else b print(return_bigger(1, 3)) # => 3
When to use it
The above cases are not realistic use cases, because if you'd like to create a named function, you can use normal functions using def.
When you'd like to use functions as arguments, lambda functions are useful.
For example, let's check a case using map.
The map function returns an iterator that applies function to every item of an iterable.
Built-in Functions — Python 3.12.1 documentation
Of course, you can create a function and use it in the map function.
l = [1, 2, 3, 4] def double(x): return x**2 print(list(map(double, l))) # => [1, 4, 9, 16]
Also, you can use the lambda function, and it makes the code simpler.
l = [1, 2, 3, 4] print(list(map(lambda x: x**2, l))) # => [1, 4, 9, 16]
Impression on Implementation
- Abbreviated notations like this may sometimes decrease readability. You should use it properly.
