Python Lambda Function Tutorial

In Python, lambda functions are succinct and unnamed functions, signifying that they do not possess a designated name. These functions are utilized to optimize and simplify brief operations, thereby enhancing the overall readability of the code.

Python Lambda Function Syntax

The syntax for a Lambda function in Python is as follows:

Example

lambda arguments : expression

Parameters:

  • Lambda is the keyword that defines a function.
  • Arguments are the input parameters, which are a list separated by commas.
  • Expression is the entity that gets evaluated and returned.

Let’s explore a practical application of a Lambda function by examining some examples:

Simple Lambda Function Example in Python

Here is an illustration of how to incorporate 10 into the parameter x:

Example

Example

#using lambda function

n = lambda x : x + 10

#printing the output, and 10 is the value of x

print(n(10))

Output:

Output

#value of n

20

Explanation:

In this instance, 'x' serves as the input parameter for the lambda function, while the expression being computed is x + 10. We supplied the value of x and displayed the resulting output.

Let us examine an additional example to gain an even clearer understanding:

Lambda Function Example with Multiple Arguments in Python

Below is an example of multiplying arguments:

Example

Example

#here x,y represent agruments

#x*y is an expression

n = lambda x, y : x * y

#printing the output n and (2,10) are the values of x and y respectively

print(n(2, 10))

Output:

Explanation:

The preceding illustration showcases how to multiply two input parameters utilizing a lambda function. The expression 'lambda x,y: xy' establishes an anonymous (lambda) function that accepts two parameters, x and y, and subsequently produces their product (xy).

Lambda with Condition Checking

Conditional expressions, such as if statements, can indeed be utilized in conjunction with lambda functions. Let’s examine an instance that demonstrates the application of conditional if statements alongside a lambda function:

Example

Example

# Lambda function to check if a number is Zero, Even, or Odd

n = lambda x: "Zero" if x == 0 else "Even" if x % 2 == 0 else "Odd"

# Value of x and printing n

print(n(5))

print(n(8))

print(n(0))

Output:

Output

Odd

Even

Zero

Explanation:

In the preceding illustration, we utilized an if statement in conjunction with a lambda function. The variable x serves as the input to the lambda function, and within the expression, we outline conditions to determine if the number is odd, even, or zero.

  • If x equals 0, it yields "Zero."
  • If not, and if x modulo 2 equals 0, it outputs "Even"; otherwise, it produces "Odd."
  • Lambda with List Comprehension

List Comprehension serves the purpose of generating a new list in a concise manner, and when paired with Lambda functions, it enables us to achieve results more efficiently. Consider the following example that demonstrates the integration of a Lambda function with List Comprehension:

Example

Example

#using Lambda functions with List Comprehension

n = [lambda a = x: a * 10 for x in range(1, 6)]

#for loop

for i in n:

    print(i())

Output:

Output

10

20

30

40

50

Explanation:

In the preceding illustration, we implemented list comprehension alongside Lambda functions.

  • lambda a = x: a * 10 defines a function that takes an input 'a' and multiplies it by 10.
  • for x in range(1,6) specifies the range of values from 1 to 5.
  • Lambda with if-else

We can utilize if-else conditional statements, which enable us to manage decision-making within the function.

Lambda Function Example using if-else statement in Python

Let us examine a scenario utilizing an if-else conditional statement:

Example

Example

# Lambda function to check whether the number is Even or Odd

n = lambda a: "Even" if a % 2 == 0 else "Odd"

# Value of x and printing n

print(a(10))

print(a(3))

print(a(0))

Output:

Output

Even

Odd

Even

Explanation:

In the preceding illustration, we employed an if-else conditional construct to ascertain whether the number is odd or even. The variable 'x' serves as the input parameter for the lambda function, while the if-else clauses constitute the expression.

The statement "Even" if x % 2 == 0 else "Odd" evaluates whether the number can be divided by 2 without leaving a remainder.

  • If it is true, it provides "Even" as the output.
  • If it is not, it yields "Odd" instead.
  • Lambda with Multiple Statements

Lambda functions allow us to carry out various operations utilizing tuples, logical operators, and expressions separated by commas. Nonetheless, it is important to note that multiple statements cannot be executed within a single lambda function. To gain a clearer understanding of this concept, let us examine an example:

Example

Example

# Addition, Multiplication, Division and Modulus

calculation = lambda a, b: (a + b, a * b, a / b, a % b)

ans = calculation(3, 4)

print(ans)

Output:

Output

(7, 12, 0.75, 3)

Explanation:

In the preceding illustration, we executed several operations, including Addition, Multiplication, Division, and Modulus. The variables a and b serve as the input parameters for the lambda function, while the arithmetic operations contained within the tuple represent the expressions that are being calculated and returned.

Using lambda with filter

In Python, the filter function takes two arguments: a function and an iterable, such as a list. This allows for an effective way to exclude elements that do not meet the specified condition, returning only those for which the condition returns True.

Python Lambda Function Example using filter Function

Let’s examine an instance of employing a lambda function in conjunction with the filter method:

Example

Example

#Filtering even numbers from a list

num = [1, 2, 3, 4, 5, 6]

is_even = filter(lambda a: a % 2 == 0, num)

print(list(is_even))

Output:

Output

[2, 4, 6]

Explanation:

In the previous illustration, we established a list referred to as 'num'. The variable 'a' serves as the input parameter for the lambda function, while the expression 'a % 2 == 0' is utilized to determine whether the number is even.

The filter function implements this criterion and eliminates the numbers that are entirely divisible by two.

Using lambda with map

In Python, the map function takes a function and a list as its parameters and produces a new list that contains the results of applying the provided function to each item in the initial list. To grasp the functionality of the map function more effectively, let’s examine an example:

Example

Example

# Square each number in a list

num = [1, 2, 3, 4]

#using the map() function

square = map(lambda x: x ** 2, num)

#printing the square

print(list(square))

Output:

Output

[1, 4, 9, 16]

Explanation:

In the example provided, we have established a list referred to as num. Here, 'x' serves as the input parameter for the lambda function, while the expression 'x ** 2' computes the square of the given number. The map function utilizes this criterion and generates a new list containing the squares of the numbers from the original list.

Using lambda with reduce

In Python, the reduce function takes two parameters: a function and an iterable (for example, a list). It yields a single value that is obtained by continuously applying the specified function to the elements of the iterable. To utilize reduce, it is necessary to import it from the functools module.

Python Lambda Function Example using reduce Function

Let’s explore the utilization of lambda functions in conjunction with the reduce function through an illustrative example:

Example

Example

#importing reduce from functools

from functools import reduce

#given input list

num_list = [2, 0, 2, 5]

#using lambda with reduce()

number = reduce(lambda x, y: x * 10 + y, num_list)

print(number)

Output:

Explanation:

In the preceding illustration, we established a list referred to as num_list. The variables 'x' and 'y' serve as the input parameters for the lambda function, while the expression is represented by 'x * 10 + y'.

It iterates over each item:

  • It starts with the first two elements: x=2, y=0, then 2*10 + 0 = 20
  • Now x=20 and y=2, then 20*10 + 2 = 202
  • In this step, x= 202 and y=5, let's calculate 202*10 + 5 = 2025

Hence, we combined the elements of the list.

Difference Between lambda and def Keyword

In Python, the lambda and def keywords exhibit a number of distinctions. Key differences include the following:

lambda function def function
It consists of a single expression with a lambda It consists of multiple lines of code.
It is Anonymous, which means without a name It must have a name
It has only a single expression statement. It can consist of many statements.
It is best for temporary and short functions. It is good for complex and reusable logic in the code.

Conclusion

Lambda Functions are concise, anonymous functions; they are used for streamlining and simplifying short tasks, and they contribute in improving the readability of the program. We can use Lambda function with:

  • Condition checking
  • List Comprehension
  • if-else
  • Multiple statements
  • Filter function
  • Map function
  • Reduce function
  • Python Lambda Functions FAQs

    1. Why should we use lambda functions in Python?

Lambda functions are characterized by a single expression statement, which contributes to code brevity and enhances readability. They lack a specific name and are ideally suited for temporary, short-term operations.

2. When should we use lambda functions in Python?

Lambda functions are particularly useful when we need brief and succinct expressions or when we intend to utilize functions such as filter, map, and reduce to enhance the efficiency and clarity of our code.

3. Difference between Lambda and def?

There are notable distinctions between Lambda and def. For instance, Lambda is defined by a single expression, while def can encompass several lines of code. Additionally, Lambda functions do not have a designated name, whereas functions defined using def must be assigned a name.

4. Can lambda functions have multiple expressions or statements?

No, lambda functions are restricted to containing only one expression.

5. Can we use if-else in a lambda function?

Indeed, it is possible to utilize conditional expressions, such as if-else statements, within a lambda function.

Input Required

This code uses input(). Please provide values below: