Guidelines

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.

Basic Structure of a Lambda Function
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:

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 with a Conditional Statement
# 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 Passing a Lambda Function as an Argument
# 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]
Mission
0 / 1

A lambda function is an anonymous function that can be written in a single line in Python.

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result