What is a Lambda Function?
A lambda function in Python is a small and anonymous functions. It’s used in cases where a quick one-off function without the need of formally defining it using def
. These functions are concise and limited to single expression.
Defining a Lambda Function?
Lambda functions are defined using the lambda
keyword followed by one or more arguments then a colon and finally a single expression. The result of the expression is automatically returned without needing the use of an explicit return statement.
When to Use Lambda Functions?
Lambda functions in Python are perfect for quick and disposable operations especially when working with higher-order functions like map()
, filter()
, and sorted()
. It enables concise and readable code for simple tasks like transformations and filtering. Use it for custom sorting or returning an anonymous function dynamically but avoid them for complex logic or multiple statements to maintain clarity and readability.
Syntax and Arguments
Syntax:
lambda arguments: expression
- Arguments: A lambda function can take multiple arguments or none. It works just like a normal function.
- Expression: This is the single line of logic or computation that the function needs to execute.
Example:
# Calculating Square of a Number square = lambda x: x ** 2 print(square(4)) # Output: 16
Multiple Arguments Lambda Function
Multiple arguments are separated by a comma.
Example:
# Finding the Maximum of Two Numbers max_value = lambda a, b: a if a > b else b print(max_value(10,20)) # Output: 20