Lambda Expressions

tags: #python/documentation/python_functions

Understanding What are Lambda Functions

In Python, an anonymous function is a Python Function that is defined without a name ("anonymous" function).

While normal functions are defined using the def keyword in Python, anonymous functions are defined using the lambda keyword:

lambda arguments: expression

The syntax of a lambda expression is the word “lambda” followed by:

Lambda Expressions Produces a Function Object

When you define a lambda expression in Python, you are creating a function object (i.e., an instance of the built-in function type/class)

Example:

# Regular function to calculate the square of a number
def square(x):
    return x ** 2

print(square(4))  # Output: 16

The equivalent lambda function:

# Lambda function to calculate the square of a number
square_lambda = lambda x: x ** 2

print(square_lambda(4))  # Output: 16

Use Cases

1. As Function Arguments

Lambda functions are often used as arguments to higher-order functions e.g., the sorted() function, where it is used to define a custom sorting key:

lst = [1, 5, 3, 8, 0]

sorted_list = sorted(lst, key=lambda x: x+2, reverse=False)
[3, 7, 5, 11, 2]
2. As Anonymous Functions

Lambda expressions are also commonly used if you need a quick, short-lived function for a specific operation.

# Using lambda as an anonymous function in a print statement
print((lambda x, y: x + y)(3, 4))
# Output: 7
Powered by Forestry.md