how to use lambda python

How to Use Lambda in Python

In Python, lambda functions (also known as anonymous functions) allow us to create small, one-line functions without using the def keyword. Lambda functions are useful when we need to define a simple function that we won’t reuse elsewhere in our code. Here’s how you can use lambda functions in Python.

Step 1: Syntax

A lambda function follows this basic syntax:

python
lambda arguments: expression

The arguments are optional, and they represent the input values that the lambda function expects. The expression is the result that the lambda function will return when called.

Step 2: Assigning to a Variable

To use a lambda function, we usually assign it to a variable. This allows us to call the function through that variable. Here’s an example:

python
add = lambda x, y: x + y

In this example, the lambda function lambda x, y: x + y is assigned to the add variable. We can now call this function by using the add variable:

python
result = add(3, 5)
print(result) # Output: 8

Step 3: Using Lambda Functions as Arguments

Lambda functions can also be used as arguments for other functions. One common example is the map() function, which applies a given lambda function to each element of an iterable. Here’s an example:

python
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]

In this example, the lambda function lambda x: x**2 squares each element of the numbers list. The map() function applies this lambda function to each element and returns a new list with the transformed values.

Step 4: Using Lambda Functions in Higher-Order Functions

Higher-order functions are functions that take other functions as arguments or return them. Lambda functions are commonly used in higher-order functions. Here’s an example using the filter() function, which filters elements from an iterable based on a given lambda function:

python
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4]

In this example, the lambda function lambda x: x % 2 == 0 checks if a number is even. The filter() function applies this lambda function to each element of the numbers list and returns a new list containing only the even numbers.

That’s it! You now know how to use lambda functions in Python. Remember that lambda functions are best suited for simple, one-line operations. If you need more complex functionality, it’s recommended to use regular functions defined with the def keyword instead.