Creating Concise Anonymous Functions with Lambda
Lambda
functions are anonymous functions used to express simple operations without a function name.
The term anonymous means that the function you write doesnβt have a name.
Unlike functions defined with the def
keyword, lambda functions are defined using the lambda
keyword, allowing for a short and concise expression.
lambda arguments: expression
In this structure, arguments
represent inputs to the function, and expression
is the operation performed on these inputs.
Hereβs a simple example of a lambda function:
# Lambda function that returns the sum of two numbers add = lambda x, y: x + y # 'add' is a variable pointing to the lambda function print(add(3, 5)) # Output: 8 # Lambda function that returns the square of a given number square = lambda x: x * x print(square(4)) # Output: 16
Beyond simple arithmetic operations like the above, you can write more complex lambda functions using conditions.
# Lambda function to check if a given number is even or odd is_even = lambda x: 'Even' if x % 2 == 0 else 'Odd' print(is_even(3)) # Output: Odd
In the code above, the is_even
lambda function uses the condition 'Even' if x % 2 == 0
to return 'Even'
if the given number x
is divisible by 0
, and 'Odd'
otherwise.
When to Use Lambda Functions?
Lambda functions have the following advantages over regular functions defined with the def
keyword:
-
Concise Function Definition: You can define simple functions in one line, keeping the code clean and easy to read.
-
Use as Function Arguments: They're ideal for passing as arguments to other functions, enhancing code flexibility and reusability.
# Example of using lambda with the filter() function numbers = [1, 2, 3, 4, 5] # Create a new list by filtering even numbers from the list 'numbers' even_numbers = filter(lambda x: x % 2 == 0, numbers) print(list(even_numbers)) # Output: [2, 4]
A lambda function is an anonymous function that can be written in a single line in Python.
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result