Python - Lambda Expressions



In Programming, functions are essential, they allows us to group the logic into the reusable blocks, making the code cleaner and easier to maintain. Generally, when we define a function we give it a name, parameters and a body.

For instance, if we need a small function that will be used only once such as sorting a list, filtering data or performing a calculation. In this cases, writing the full function feels like unnecessary, this is where we use the Lambda Expressions. Let's dive into the tutorial to understand more about the lambda expressions.

Lambda Expressions

A Lambda Expressions is a used to define a small, nameless (anonymous) function in a single line. We use lambda to create a function instantly and pass it wherever a function is need, Instead of writing the complete function with the def keyword (Python) or similar keyword in other languages. For example, instead of writing:

def add(a, b):
    return a + b

We can use the lambda expression as:

add = lambda a, b: a + b

Both perform the same operation adding two numbers, but the lambda version is shorter and can be created at the point of use, without defining it separately.

Syntax

Following is the syntax for lambda expressions:

lambda parameters: expression

Following are the parameters -

  • lambda − It indicates the keyword.
  • parameters − They are the inputs, just like function arguments.
  • expression − It indicates the expression to gets evaluated and returned.

Use of Lambda Expressions

The lambda expressions are not meant to replace all the regular functions. They are useful in specific situations:

  • Inline Usage − They can be used directly where the function is needed, avoiding the need to create a separate function.
  • Conciseness − They allows us to define the simple function in one line without writing a full def block.
  • Functional Programming − They integrate smoothly with higher-order functions like map(), filter() and reduce().

Examples of Using Lambda Expressions

Let's explore some of the practical examples to understand more about the Lambda expressions.

Example 1

Consider the following example, where we are going to use the lamba with the map() function.

array = [1, 2, 3]
result = list(map(lambda x: x ** 2, array))
print(result)

The output of the above program is -

[1, 4, 9]

Example 2

In the following example, we are going to use the lambda with the filter() function.

array = [5,10,15,20]
result = list(filter(lambda x: x % 2 == 0, array))
print(result)

Following is the output of the above program -

[10, 20]

Example 3

Let's look at the following example, where we are going to use the lambda with the sorted() function.

array = ['Ravi', 'Ram', 'Ravan', 'Richel']
result = sorted(array, key=lambda x: len(x))
print(result)

The output of the above program is -

['Ram', 'Ravi', 'Ravan', 'Richel']
Advertisements