Python Lambda Functions

Demystify Python's lambda functions with our comprehensive guide. Learn how to create anonymous functions, use lambda expressions, and apply practical examples for efficient Python programming
E
Edtoks3:30 min read

Lambda functions in Python, also known as anonymous functions, are small and concise functions that can have any number of arguments but can only have one expression. They are often used for short, simple operations where defining a full function using def would be overkill. Lambda functions are particularly useful in functional programming constructs like map(), filter(), and reduce(). Here's how to use them:

Lambda Function Syntax

The basic syntax of a lambda function is as follows:

lambda arguments: expression

lambda: The keyword used to define a lambda function.

arguments: The input parameters or arguments to the function.

expression: The operation to perform on the arguments.

Lambda functions can have multiple arguments, but they must be separated by commas. The expression is evaluated and returned as the result of the lambda function.

Example 1: Simple Lambda Function

# Define a lambda function that adds two numbers
add = lambda x, y: x + y

# Call the lambda function
result = add(2, 3)
print(result)  # Output: 5

In this example, we define a lambda function add that takes two arguments and returns their sum.

Steps to Convert a Simple Function to a Lambda Function:

To convert a simple function into a lambda function, follow these steps:

Step 1: Identify the function and its arguments.

Step 2: Write the lambda keyword.

Step 3: List the arguments separated by commas.

Step 4: Write a colon :.

Step 5: Define the expression that the function will return.

Here's an example of converting a simple function to a lambda function:

Example 2: Converting a Simple Function to a Lambda Function

Consider this simple function that calculates the square of a number:

def square(x):
    return x ** 2

You can convert it to a lambda function as follows:

# Convert the simple function to a lambda function
square = lambda x: x ** 2

# Call the lambda function
result = square(4)
print(result)  # Output: 16

The lambda function, in this case, takes one argument x and returns its square.

Use Cases for Lambda Functions

Lambda functions are often used when you need a small, simple function for a short period, and you don't want to define a full function using def. They are commonly used with functional programming constructs like map(), filter(), and reduce(). Here are some use cases:

1. Sorting by a Custom Key:

You can use lambda functions to specify custom sorting keys when sorting lists of objects.

students = [
    {"name": "Alice", "score": 85},
    {"name": "Bob", "score": 92},
    {"name": "Charlie", "score": 78},
]

sorted_students = sorted(students, key=lambda x: x["score"])

2. Filtering Elements

Lambda functions are useful when filtering elements from a list.

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)

3. Mapping Elements

Lambda functions can be used with map() to apply a function to each element in a list.

numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x**2, numbers)

4. Creating Short Inline Functions

When you need a small function for a short calculation.

result = (lambda x, y: x + y)(3, 4)

While lambda functions are handy for certain tasks, they should be used judiciously. For more complex or multi-line functions, it's better to define a regular function using def for the sake of readability and maintainability.

 

Let's keep in touch!

Subscribe to keep up with latest updates. We promise not to spam you.