Published on

What is a lambda function?

Authors
  • avatar
    Name
    hwahyeon
    Twitter

This is the code I encountered:

Dense(1) # res = 20
tf.keras.layers.Lambda(lambda x: x * 400)

Wait... lambda??

What is a lambda function?

A lambda function is used to define an anonymous function. It's useful when you need a simple, one-liner function and don’t want to use the def keyword, which can be a bit too verbose for such cases.

A lambda function consists of parameters and an expression (or result). Let's look at the examples below.

Example:

add = lambda x, y: x + y
result = add(1, 2)
print(result) # 3

In this case, x and y are the parameters, and the result is x + y.

check = lambda x: "Positive" if x > 0 else "Negative"
print(check(-1))  # Negative

In the example above, x is the parameter, and the part after the colon is the expression.

Applying a lambda function with map()

numbers = [1, 2, 3]
doubled_numbers = list(map(lambda x: x * 2, numbers))
print(doubled_numbers)  # [2, 4, 6]

The map() function applies the lambda function to each element in a list or any iterable.

Using lambda with filter()

numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4, 6]

The filter() function returns only the elements that satisfy the given condition in the lambda function.

Reference

Lambda layer