Lambda Function for Python Beginners

A lambda function may be unfamiliar with Python beginners. Certainly, the lambda function is not always necessary, but if it is used adequately, it will be possible to execute arbitrary processing with a compact description.

What is a lambda function? Main two features are as follows.

1. Anonymous function with a return value
2. Described with one sentence

Let’s start with a simple example to imagine!
We will see two example codes as follows. And, note that both examples have the same function, returning the square of the input variable.

Standard Style

This example is the one you might be familiar with.

def square(x):
    return x*x

ret = square(2)
print(ret)

>> 4

Lambda function Style

With a lambda-function style, you can express the same function above with just one sentence!

ret = (lambda x: x*x)(2)
print(ret)

>> 4

The syntax of lambda functions is below.

Syntax:    lambda x: f(x)

“lambda” just claims that “This is a function”. And, the function is “f(x)” with the argument “x”, equaling to the returned value.

Since the whole sentence “lambda x: f(x)” is the function itself, we use parentheses for giving an argument to x as in the above example.

Example

Let’s square each element of the list.

A standard expression by “for loop” is as follows.

num_list = [1, 2, 3, 4]
for i in range(len(num_list)):
    num_list[i] = num_list[i]*num_list[i]
print(num_list)

>> [1, 4, 9, 16]

On the other hand, we can rewrite “for loop” into the one sentence with lambda functions.

num_list = [1, 2, 3, 4]
list( map(lambda x: x*x, num_list) )

print(num_list)

>> [1, 4, 9, 16]

map() function is to perform the same processing for each element of list.

Syntax:    map(function, iterator)

You can interpret “function” and “iterator” as just like “f(x)” and “x”, respectively.

Actually, there is a deep world of map() function, so the details of an explanation will NOT be here. However, in relation to map() function, lambda functions will be a powerful tool when used together with Pandas.

Summary

In this article, we saw the brief introduction of the lambda function. The usage of this function makes it possible to adopt a compact expression. Consequently, a low-code habit may improve the interpretation and the maintainability of your codes.