Lambda

Lambda Functions in Python

A lambda function is a concise and anonymous way to create a small function in Python. Unlike regular functions defined with the def keyword, lambda functions are often used for short-term operations and can only contain a single expression.

Syntax

The basic syntax for a lambda function is as follows:

lambda arguments : expression

Here, the expression is evaluated, and the result is returned.

Basic Examples

Let’s look at some basic examples of lambda functions:

Adding a Number

Here is a lambda function that adds 10 to the argument a and returns the result:

x = lambda a: a + 10
print(x(8))  

Multiplying Two Numbers

This lambda function multiplies two arguments, a and b, and returns the result:

x = lambda a, b: a * b
print(x(7, 3))  

Summing Multiple Numbers

Here, the lambda function sums three arguments, a, b, and c, and returns the result:

x = lambda a, b, c: a + b + c
print(x(4, 5, 1))  

Using Lambda Functions in Higher-Order Functions

The true power of lambda functions shines when they are used within other functions, especially when the lambda function is an anonymous function passed as an argument.

Creating Multipliers

Consider a function that creates a lambda function to multiply a given number by another value:

def create_multiplier(n):
    return lambda a: a * n

Using this function, you can create specific multipliers, such as a doubler or a tripler:

Doubling Numbers

my_doubler = create_multiplier(2)
print(my_doubler(12))  

Tripling Numbers

my_tripler = create_multiplier(3)
print(my_tripler(12))  

Using Multiple Functions

You can create multiple lambda functions using the same base function:

my_doubler = create_multiplier(2)
my_tripler = create_multiplier(3)

print(my_doubler(12))  
print(my_tripler(12))  

When to Use Lambda Functions

Lambda functions are ideal for short-term, anonymous operations that are not meant to be reused elsewhere. They are often used in conjunction with functions like map(), filter(), and sorted() where a short function is needed for a brief period.

Practice Exercise

Create a lambda function that takes a single parameter a and returns the same value:

x = lambda a: a
print(x(15))  

Feel free to experiment with lambda functions to understand their use cases and limitations better.

Leave a Comment

Free & easy backlink link building. Direct hire fdh.