Python Lambda Function
A lambda function is a small, anonymous (nameless) function defined using the lambda keyword. It can accept any number of arguments, but it can contain only one expression.
Syntax
lambda arguments: expression
arguments: input valuesexpression: a single expression that is evaluated and returned automatically.
When to Use Lambda Functions
Use lambda functions for short, simple, one-time operations, especially passing them as arguments to higher-order functions. For complex logic or reusable functionality, prefer a regular def function to keep your code readable.
Examples
Basic Lambda Functions
Let’s say you want to find the square of a number. Here is how you can do it using a normal function and then using a lambda function.
Using a normal function
def square(x):
return x ** 2
print(square(5)) # Output: 25
Using a lambda function
A lambda function can be assigned to a variable and called like a regular function.
square = lambda x: x ** 2
print(square(5)) # Output: 25
Multiple Arguments
Lambda function can accept multiple arguments, just like regular functions.
add = lambda a, b: a + b
print(add(2, 3)) # Output: 5
Default Values in Lambda
You can assign default values to lambda function parameters, which are used when no argument is provided for that parameter.
power = lambda x, y=2: x ** y
print(power(5)) # Output: 25
print(power(5, 3)) # Output: 125
Using Lambda Functions With Built-in Functions
Lambda functions are commonly used as arguments to higher-order functions that require a function object as input.
1. With map()
The map() function applies a function to each item in an iterable.
For example:
numbers = [1, 2, 3, 4]
# Square every number
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # Output: [1, 4, 9, 16]
In this example, a lambda function is used to square a number. The map() function takes each element from the numbers list and passes it to the lambda function. The function returns a squared value for each element, which is collected into a map object. The list() function then converts the map object into a list.
(2) With filter()
The filter() function filters elements from an iterable based on a condition.
For example:
numbers = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output; [2, 4]
In this example, a lambda function is used to check if a number is even. The filter() function takes each element from the numbers list and passes it to the lambda function. The function returns True for elements satisfy the condition and False for those that do not. Only the elements for which the function returns True are collected into a filter object. The list() function then converts the filter object into a list.
(3) With sorted()
The sorted() function returns a new list containing the elements of any iterable in sorted order.
Suppose you have a list of tuples where each tuple contains person’s name and age. If you want to sort this list based on age, here is how you do it:
person = [("Noah", 25), ("Alice", 22), ("James", 30), ("Emma", 18)]
sorted_person = sorted(person, key=lambda x:x[1])
print(sorted_person) # Output: [('Emma', 18), ('Alice', 22), ('Noah', 25), ('James', 30)]
The sorted() function takes an iterable (in our case list) as its first argument and an option key parameter as its second argument. The key parameter tells Python how to sort the elements.
In this example, a lambda function is passed as the key. The lambda function takes each tuple from the list and returns the value at index 1, which represents the age. Index 0 contains the name, but is not used for sorting in this case.
Python uses the values returned by the lambda function to sort the tuples in ascending order, while keeping each name paired with its corresponding age.
As a result, the list is ordered from the youngest person to the oldest.
If you want to sort the list in descending order by age, you can use the reverse parameter of the sorted() function.
person = [("Noah", 25), ("Alice", 22), ("James", 30), ("Emma", 18)]
sorted_person = sorted(person, key=lambda x:x[1], reverse=True)
print(sorted_person) # Output: [('James', 30), ('Noah', 25), ('Alice', 22), ('Emma', 18)]
Lambda Function With Conditional Logic
You can include a conditional expression (ternary operator) inside a lambda function.
For example:
check_age = lambda age: "Adult" if age >= 18 else "Minor"
print(check_age(20)) # Output: Adult
print(check_age(15)) # Output: Minor
In this example, the lambda function returns "Adult" if the age is 18 or older, and "Minor" otherwise.
Lambda in List Comprehensions
You can use a lambda function within a list comprehension to quickly apply an operation to each item in a list.
For example:
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Lambda function to square a number
square = lambda x: x**2
# Use lambda function inside list comprehension
squared_numbers = [square(n) for n in numbers]
print(squared_numbers) # Output: [1, 4, 9, 16, 25]