Register Login

Python Lambda Functions

Updated May 30, 2023

In Python, users can use functions without a name and are called anonymous functions. Users use the def keyword, which creates a Python function to initialize a typical function.

But the lambda function is exceptional with special characteristics, which we will study in this article. This article will also highlight all the examples and explanations of programs based on the lambda function.

What is a lambda function?

The lambda is a keyword in Python that specifies an anonymous function. Users can use arguments in the lambda function that acts as a placeholder and stores the value they will pass into this function.

A lambda function can accept multiple variables or arguments based on what users want to perform. But it can have only one expression.

Syntax:

lambda arguments : expression

How can users define the lambda function?

  • First, users must use the lambda keyword in Python to define the anonymous function.
  • Then, they set the number of required argument or arguments, which is the placeholder. This placeholder is a variable that users can use to store the item they want to add to the function expression.
  • Lastly, they can set the condition or any expression in the function they want to run in the lambda function.

Note:

  • Users can add any number of arguments in the lambda function but can use a single expression, which the function will evaluate and return.
  • Users can easily use lambda functions, available anytime and wherever function objects are needed.
  • One of the most critical points is users can use only one expression in the lambda functions as it is syntactically restricted.
  • Lambda function has several use cases in different fields of programming and other types of expressions in functions.

Example 1:

Code Snippet:

a = 'This is Python Lambda Function'
demo = lambda string: string.upper()[::-1]
print(demo(a))

Output:

Explanation:

In the above code snippet, we used the lambda function in the variable "demo" to convert a string to reverse the string to its upper case.

Example 2:

Code Snippet:

demo = lambda x: x + 8
print(demo(2))

Output:

Explanation:

Here, we used a single argument, "x," to store a number and added this to the demo variable with the lambda function.

Example 3: Checking conditions with a lambda function

Code Snippet:

fn = lambda n: f"{n:e}" if isinstance(n, int) else f"{n:,.2f}"
print("The format of integer:", fn(4564757))
print("The format of float:", fn(762133.353789765))

Output:

Explanation:

In this example, we checked a condition with if-else and evaluated whether the number was an integer or floating point. Then, we specified the lambda function to evaluate this conditional statement.

When and why should users use the lambda function in Python?

When users need to create a simple Python program, they can use this lambda function which increases the readability of the code. There are several cases in programming where users do not need to use complex structures like if-else, for loops, etc., and simply use the anonymous keyword to create a function.

Lambda functions are efficient in more or less many cases where users want to initialize a Python function that will store simple expressions. These expressions are generally a single line of a statement.

Thus, these functions are practical when users want to create a program using the function once, improving readability.

Difference between lambda (anonymous function) and def keyword

Def Lambda
The interpretation is easy. The interpretation might get tricky.
Used the def keyword Used the lambda keyword
Users can add any number of execution statements within the def function. But using the lambda function, users can add a limited number of operations.
The def function specifies the function name in the local namespace The lambda function does not compulsorily specify the function name in the local namespace
Slow execution time Fast Execution time
Users need to explicitly define the return execution that will return the object from the function. No return statement

Code Snippet:

def cube(a):
	return a*a*a
demo = lambda a: a*a*a
print(" Here, we used the def keyword to create a function and find the cube of two: ", cube(2))
print(" Here, we used the lambda keyword to create a function and find the cube of two: ", demo(2))

Output:

Uses of Lambda Function with examples

Example 1: Using the lambda with multiple statements

We cannot directly use multiple statements in the Lambda functions, but we can create two Lambda functions. Then, we can call this second lambda function into the parameter of the first function. Let us see how it works with the following example:

Code Snippet:

a = [[1, 2, 3], [8, 16, 26, 32], [2, 4, 6, 8]]
b = lambda x: (sorted(i) for i in x)
c = lambda x, i : [y[len(y)-2] for y in i(x)]
result = c(a, b)
print(result)

Output:

Explanation:

Here, we have created two lambda functions where the first function will sort each sublist of the given list. Then, pass this list into the parameter of the second lambda function, and it will return the n-2 items from the sorted list. Here, the "n" indicates the length of the sublist.

Example 2: Using the lambda function with list comprehension

It is an example of the lambda function with a list comprehension method.

Code Snippet:

a = [lambda argument = i: argument * 100.0 for i in range(1, 6)]
for val in a:
	print(val())

Output:

Explanation:

In this example, we have created a new lambda function on every iterable operation within the list comprehension with the default argument of i, where i indicates the current value in the iteration.

Then, we used the for loop to call the same function object with the default argument using the val() and got the desired value. Thus, the variable "a" stores the list of lambda function objects.

Conclusion

We hope this article has given a crisp idea of how the lambda function works in Python and its different examples. Using a lambda function in some cases can be more advantageous, instead of creating a function using the def keyword.

This article also highlighted examples of when users can use this function and the difference between def and lambda functions.


×