Python Lambda
Learn all about Python Lambda in this comprehensive tutorial.
- •A lambda function is a small anonymous function.
- •The expression is executed and the result is returned:
- •The power of lambda is better shown when you use them as an anonymous function inside another function.
- •Lambda functions are commonly used with built-in functions like map(), filter(), and sorted().
Lambda Functions
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
Syntax
The expression is executed and the result is returned:
Lambda functions can take any number of arguments:
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an anonymous function inside another function.
Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number:
Use that function definition to make a function that always doubles the number you send in:
Or, use the same function definition to make a function that always triples the number you send in:
Or, use the same function definition to make both functions, in the same program:
Lambda with Built-in Functions
Lambda functions are commonly used with built-in functions like map(), filter(), and sorted().
The map() function applies a function to every item in an iterable:
The filter() function creates a list of items for which a function returns True:
The sorted() function can use a lambda as a key for custom sorting:
Module quiz
2 questionsWhich of the following is true about Python Lambda?
What is the most common pitfall when working with Python Lambda?
Answer all questions to submit.