Overview: Lambda Functions in Python
Sometimes, a program needs a small function for a single task. Creating a regular function for that task can add extra code when the operation is simple and used only in one place.
For example, suppose a program needs to double a value before using it. Creating a named function just for this small operation may make the code longer than necessary.
Python provides lambda functions for such situations. They let you create a small function without writing a full function definition.
Introduction: What Are Lambda Functions in Python?
A lambda function is a small function created with the lambda keyword. It can accept arguments and return the result of a single expression.
Unlike a regular function created with def, a lambda function does not require a name when you create it.
lambda x: x * 2
Explanation Here, x is the argument, and x * 2 is the expression that produces the result. The lambda function takes a value for x, doubles it, and returns the result.
How to Create Lambda Functions in Python
Once you understand what a lambda function is, the next step is to create one. A lambda function uses a shorter syntax than a regular function created with def.
Syntax: Lambda Function
A lambda function uses the following syntax:
lambda arguments: expression
lambda— the keyword that starts the lambda function.arguments— the input values the function receives.:— separates the arguments from the expression.expression— the operation that produces the result.
The arguments are the values the lambda function receives. The expression uses those values and produces the result.
For example, this lambda function takes a number and doubles it:
double = lambda x: x * 2
print(double(5))
# Output:
10
Explanation: Here, x is the argument, and x * 2 is the expression. When the lambda receives the value 5, it returns twice that value, which is 10.
Lambda Function Arguments in Python
A lambda function can have different numbers of arguments depending on the input values it needs.
Let’s first understand these argument patterns. Later, we’ll see how to call a lambda function with those arguments.
- One Argument
- Multiple Arguments
- No Arguments
1. One Argument
A lambda function can accept a single argument.
lambda x: x * 2
Explanation Here, x is the only argument. The lambda takes a value for x and returns twice that value.
2. Multiple Arguments
A lambda function can also accept multiple arguments. Separate the arguments with commas.
lambda a, b: a + b
Explanation Here, a and b are the two arguments. The lambda adds their values and returns the result.
3. No Arguments
A lambda function can have no arguments when it does not need any input values.
lambda: "Hello"
Explanation Here, the lambda has no arguments and contains only the expression "Hello".
How to Call Lambda Functions in Python
Lambda functions can be called just like a regular function. The process involves two basic steps:
1. Assigning a Lambda Function to a Variable
You can assign a lambda function to a variable when you want to reuse it instead of writing the lambda expression each time.
double = lambda x: x * 2
print(double(5))
# Output:
10
Explanation Here, the lambda function is assigned to the variable double. The variable refers to the lambda function, so you can use double to call it.
2. Calling the Lambda Function
To call a lambda function stored in a variable, write the variable name followed by parentheses and pass the required argument.
double = lambda x: x * 2
result = double(8)
print(result)
# Output:
16
Explanation Here, double(8) calls the lambda function and passes 8 to x. The lambda evaluates x * 2 and returns 16, which is stored in result.
Lambda Functions With Python Built-in Functions
Python’s built-in functions can accept a lambda function when they need a small piece of custom logic. Instead of defining a separate function with def, you can pass the lambda directly to the built-in function.
Use the following links to explore each built-in function:
- Lambda Functions With
sorted() - Lambda Functions With
filter() - Lambda With
min()andmax() - Lambda Functions With
map()
1. Lambda Functions With sorted()
The sorted() function can sort a collection based on a value you choose. When the sorting value is not the item itself, you can use a lambda function with the key parameter to tell sorted() which value to use.
A. Sorting by a Specific Value
A lambda function can select the value that sorted() should use for comparison. This is useful when each item contains more than one value and you want to sort by a specific one.
students = [
("Asha", 85),
("Rahul", 92),
("Meera", 78)
]
result = sorted(students, key=lambda student: student[1])
print(result)
# Output:
[('Meera', 78), ('Asha', 85), ('Rahul', 92)]
Explanation: Here, lambda student: student[1] accesses the value at index 1 in each tuple. This value contains the student’s marks, so sorted() uses the marks to arrange the students from lowest to highest.
The algorithm works as follows:
- Start with the list of students.
sorted()passes each student tuple to the lambda.student[1]picks the marks, andsorted()uses them to compare the students.sorted()returns the students arranged from the lowest mark to the highest.
B Sorting a List of Tuples
A list of tuples can contain different values for each item. You can use a lambda function to select the tuple value that should determine the sorting order.
products = [
("Laptop", 75000),
("Mouse", 1500),
("Keyboard", 3000)
]
result = sorted(products, key=lambda product: product[1])
print(result)
# Output:
[('Mouse', 1500), ('Keyboard', 3000), ('Laptop', 75000)]
Explanation Here, lambda product: product[1] selects the price from each tuple. The sorted() function uses these prices to arrange the products from lowest to highest.
The algorithm works as follows:
- Start with the list of products.
sorted()passes each product tuple to the lambda.product[1]picks the price, andsorted()uses the prices to compare the products.sorted()returns the products arranged from the lowest price to the highest.
C. Sorting a List of Dictionaries
You can also use a lambda function to sort a list of dictionaries by the value of a specific key.
students = [
{"name": "Asha", "marks": 85},
{"name": "Rahul", "marks": 92},
{"name": "Meera", "marks": 78}
]
result = sorted(students, key=lambda student: student["marks"])
print(result)
# Output:
[{'name': 'Meera', 'marks': 78},
{'name': 'Asha', 'marks': 85},
{'name': 'Rahul', 'marks': 92}]
Explanation Here, lambda student: student["marks"] accesses the "marks" value from each dictionary. The sorted() function uses those values to arrange the students from the lowest marks to the highest.
The algorithm works as follows:
- Start with the list of students.
sorted()passes each student dictionary to the lambda.student["marks"]picks the marks, andsorted()uses them to compare the students.sorted()returns the students arranged from the lowest marks to the highest.
2. Lambda Functions With filter()
The filter() function selects items from an iterable based on a condition. You can use a lambda function with filter() when the condition is simple and only needed for that filtering operation.
A. Filtering Tuple Values With Lambda
A lambda function can check each value in a tuple and return True or False. The filter() function keeps the tuple values for which the lambda returns True.
numbers = (10, 15, 20, 25, 30)
result = filter(lambda x: x > 20, numbers)
print(tuple(result))
# Output:
(25, 30)
Explanation Here, lambda x: x > 20 checks whether each tuple value is greater than 20. The filter() function keeps the values for which the condition is True.
The algorithm works as follows:
- Start with the tuple of numbers.
filter()passes each value from the tuple to the lambda.- The lambda checks each value and returns
TrueorFalse. filter()keeps the values for which the lambda returnsTrue.tuple()converts the filtered result into a tuple, whichprint()displays.
B. Filtering a List of Numbers
You can use a lambda with filter() to select numbers that meet a specific condition, such as finding only even numbers from a list.
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
# Output:
[2, 4, 6]
Explanation Here, lambda x: x % 2 == 0 checks whether each number is divisible by 2 without a remainder. The filter() function keeps the numbers that satisfy this condition.
The algorithm works as follows:
- Start with the list of numbers.
filter()passes each number to the lambda.- The lambda checks whether the number is even and returns
TrueorFalse. filter()keeps the numbers for which the lambda returnsTrue.list()converts the filtered result into a list, whichprint()displays.
C. Filtering Strings With Lambda
A lambda function can also filter strings based on a condition. For example, you can select strings that contain more than a certain number of characters.
names = ["Asha", "Rahul", "Meera", "John"]
result = filter(lambda name: len(name) > 4, names)
print(list(result))
# Output:
['Rahul', 'Meera']
Explanation Here, lambda name: len(name) > 4 checks the length of each name. The filter() function keeps the names that contain more than four characters.
The algorithm works as follows:
- Start with the list of names.
filter()passes each name to the lambda.- The lambda checks whether the name has more than four characters and returns
TrueorFalse. filter()keeps the names for which the lambda returnsTrue.list()converts the filtered result into a list, whichprint()displays.
3. Lambda With min() and max()
The min() and max() functions can also use a lambda with their key parameter. This is useful when you want to find the smallest or largest item based on a specific value.
students = [
("Asha", 85),
("Rahul", 92),
("Meera", 78)
]
highest = max(students, key=lambda student: student[1])
lowest = min(students, key=lambda student: student[1])
print(highest)
print(lowest)
# Output:
('Rahul', 92)
('Meera', 78)
Explanation Here, lambda student: student[1] tells min() and max() to compare students using their marks. The second value in each tuple contains the student’s marks.
The algorithm works as follows:
- Start with a list of students. Each tuple contains the student’s name at index
0and marks at index1. - Pass the
studentslist tomax()withlambda student: student[1]as thekey. max()passes each student tuple to the lambda function one at a time.- For each tuple,
student[1]accesses the student’s marks at index1and returns them tomax()as the value to compare. max()compares the marks and returns the tuple with the highest mark.min()uses the same lambda to access the marks from each tuple and returns the tuple with the lowest mark.- The
print()statements display the students with the highest and lowest marks.
4. Lambda Functions With map()
The map() function applies a function to each item in an iterable and produces the transformed results. You can use a lambda function with map() when the transformation is simple and only needed for that operation.
A. Transforming Values With Lambda
A lambda function can transform each value in a list. The map() function applies the lambda to every value and produces the transformed results.
numbers = [10, 20, 30, 40]
result = map(lambda x: x * 2, numbers)
print(list(result))
# Output:
[20, 40, 60, 80]
Explanation Here, lambda x: x * 2 multiplies each number by 2. The map() function applies this operation to every number.
The algorithm works as follows:
- Start with the list of numbers.
map()passes each number from the list to the lambda.- The lambda multiplies each number by
2and returns the result. map()produces the transformed values.list()converts the mapped result into a list, whichprint()displays.
B. Applying Lambda to Two Iterables
The map() function can apply a lambda to two iterables at the same time. The lambda receives one value from each iterable and uses them together.
numbers1 = [10, 20, 30]
numbers2 = [1, 2, 3]
result = map(lambda x, y: x + y, numbers1, numbers2)
print(list(result))
# Output:
[11, 22, 33]
Explanation Here, lambda x, y: x + y adds one value from numbers1 to the corresponding value from numbers2. The map() function applies the lambda to both iterables in parallel.
The algorithm works as follows:
- Start with the two lists of numbers.
map()takes one value from each list and passes them to the lambda.- The lambda adds the two values and returns the result.
map()repeats the process for the remaining values.list()converts the mapped result into a list, whichprint()displays.
When the iterables have different lengths, map() stops when the shortest iterable is exhausted.
map() With Lambda vs List Comprehension
Both map() with a lambda and a list comprehension can transform values in an iterable. They use different approaches to perform the same type of operation.
numbers = [10, 20, 30, 40]
# Using map() with lambda
result = map(lambda x: x * 2, numbers)
print(list(result))
# Output:
[20, 40, 60, 80]
# Using a list comprehension
result = [x * 2 for x in numbers]
print(result)
# Output:
[20, 40, 60, 80]
Both approaches multiply each number by 2 and produce the same result.
- The
map()version passes the transformation to a lambda. - The list comprehension places the transformation directly inside the expression.
The algorithm for the map() version works as follows:
- Start with the list of numbers.
map()passes each number to the lambda.- The lambda multiplies each number by
2. map()produces the transformed values.list()converts the mapped result into a list.
The algorithm for the list comprehension works as follows:
- Start with the list of numbers.
- The list comprehension takes each number from the list.
- It multiplies the number by
2. - It adds the transformed value to the new list.
- The completed list is stored in
result.
For simple transformations, choose the form that makes the code easier to read. Both approaches can produce the same result.
Lambda Functions With reduce()
The reduce() function combines the values in an iterable and produces a single result. You can use a lambda function with reduce() when the operation is simple and only needed for that reduction.
Explore the different ways to use lambda functions with reduce():
1. Using Lambda With reduce()
Python provides reduce() in the functools module. It repeatedly applies a function to two values at a time, using the previous result in the next calculation.
from functools import reduce
numbers = [10, 20, 30, 40]
result = reduce(lambda x, y: x + y, numbers)
print(result)
# Output:
100Explanation: Here, lambda x, y: x + y adds two values at a time. The reduce() function uses each result in the next addition until it processes all the numbers.
The algorithm works as follows:
- Start with the list of numbers.
reduce()takes the first two numbers and passes them to the lambda.- The lambda adds the two numbers and returns the result.
reduce()uses that result with the next number.- The process continues until all numbers are processed.
reduce()returns the final result, whichprint()displays.
2. Calculating a Product With reduce()
You can use reduce() with a lambda to multiply all values in an iterable. This is useful when you need one product from several numbers.
from functools import reduce
numbers = [2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result)
# Output:
120Explanation: Here, lambda x, y: x * y multiplies two values at a time. The reduce() function carries each product into the next multiplication.
The algorithm works as follows:
- Start with the list of numbers.
reduce()multiplies the first two numbers.- The lambda returns the product.
reduce()multiplies that product by the next number.- The process continues until all numbers are processed.
reduce()returns the final product, whichprint()displays.
3. When reduce() Is Useful
reduce() is useful when several values need to be combined into one result through a repeated operation. For simple totals, products, maximum values, or minimum values, Python’s built-in functions can often make the code clearer.
from functools import reduce
numbers = [12, 7, 25, 18, 9]
result = reduce(lambda x, y: x if x > y else y, numbers)
print(result)
# Output:
25Explanation: Here, the lambda compares two values and returns the larger one. The reduce() function continues comparing the returned value with the next number until it finds the largest value.
The algorithm works as follows:
- Start with the list of numbers.
reduce()passes the first two numbers to the lambda.- The lambda compares the two numbers and returns the larger value.
reduce()compares that value with the next number.- The process continues until all numbers are compared.
reduce()returns the largest value, whichprint()displays.
Use reduce() when the goal is to combine multiple values into one result. For simple totals, products, or other common operations, Python’s built-in functions can often make the code clearer.
Passing Lambda Functions to Other Functions
A lambda function can be passed to another function as an argument. The receiving function can then use the lambda to perform an operation.
A. Passing a Lambda as an Argument
You can pass a lambda directly when calling a function. The function receives the lambda and can call it when needed.
def calculate(a, b, operation):
return operation(a, b)
result = calculate(10, 5, lambda x, y: x + y)
print(result)
# Output:
15
Explanation: Here, lambda x, y: x + y is passed to calculate() as the operation argument. The function calls the lambda with 10 and 5 and returns the result.
The algorithm works as follows:
- Define the
calculate()function with two values and an operation. - Call
calculate()with10,5, and a lambda function. calculate()stores the lambda in theoperationparameter.- The function calls
operation(a, b), which runs the lambda. - The lambda adds
10and5and returns15. calculate()returns the result, whichprint()displays.
B. Using Lambda for Custom Behavior
A function can accept a lambda to change how it processes data. This allows the same function to perform different operations without changing its code.
def apply_operation(numbers, operation):
return [operation(x) for x in numbers]
numbers = [1, 2, 3, 4]
squares = apply_operation(numbers, lambda x: x ** 2)
doubles = apply_operation(numbers, lambda x: x * 2)
print(squares)
print(doubles)
# Output:
[1, 4, 9, 16]
[2, 4, 6, 8]
Explanation: Here, apply_operation() uses the lambda passed through the operation parameter. The first lambda calculates the square of each number, while the second lambda doubles each number.
The algorithm works as follows:
- Define
apply_operation()with a list and an operation. - Pass the list of numbers and a lambda that calculates the square of each number.
- The function applies the lambda to each number and creates a new list.
- Pass the same list and a different lambda that doubles each number.
- The function applies the new lambda to each number and creates another list.
print()displays both results.
Passing a lambda as an argument is useful when a function needs a small, custom operation without requiring a separate function definition.
Lambda Functions vs Regular Functions
Python lets you create functions with both lambda expressions and the def statement. Both can accept arguments and return results, but they use different syntax and are useful in different situations.
Syntax Comparison
A lambda function uses the lambda keyword followed by its arguments and a single expression. A regular function uses the def statement, a function name, parameters, and an indented function body.
# Lambda function syntax
lambda arguments: expression
# Regular function syntax
def function_name(arguments):
return expressionThe two syntaxes have different structures. A lambda function places its arguments and expression on the same line, while a regular function uses a named definition with an indented body.
Example Comparison
For example, both a lambda function and a regular function can add two numbers:
# Lambda function
add = lambda x, y: x + y
print(add(10, 5))
# Output:
15
# Regular function
def add(x, y):
return x + y
print(add(10, 5))
# Output:
15Explanation: Both functions receive 10 and 5 and return 15. The lambda performs the addition in a single expression, while the regular function uses a function body and a return statement.
Key Differences
| Feature | Lambda Function | Regular Function |
|---|---|---|
| Keyword | Uses lambda | Uses def |
| Function Name | Does not require a name when used directly | Requires a name in the function definition |
| Function Body | Contains a single expression | Can contain multiple statements |
| Return Value | The expression result is returned automatically | Normally uses return to return a value |
| Typical Use | Short, simple operations | Complex or reusable operations |
When Lambda Is a Good Choice
A lambda function works well for a short operation that you need only in one place. It is especially useful when another function expects a function as an argument.
numbers = [1, 2, 3, 4, 5]
result = list(map(lambda x: x * 10, numbers))
print(result)
# Output:
[10, 20, 30, 40, 50]Explanation: Here, the lambda multiplies each number by 10. The operation is short and only used by map(), so a separate function is not necessary.
Use a lambda when:
- The operation is short and simple.
- You need the function for a single operation.
- Another function expects a function as an argument.
- A named function would add unnecessary code.
When a Regular Function Is Better
A regular function is a better choice when the operation needs several statements, a clear name, or repeated use throughout a program.
def calculate_discount(price, discount):
discount_amount = price * discount / 100
final_price = price - discount_amount
return final_price
print(calculate_discount(1000, 10))
# Output:
900.0Explanation: Here, the function performs multiple steps to calculate the final price. A regular function makes those steps easier to read and gives the operation a meaningful name.
Use a regular function when:
- The operation requires multiple statements.
- The function needs a meaningful name.
- You need to reuse the function in several places.
- The logic needs comments or detailed explanation.
- The function performs a more complex task.
Choose a lambda for a short, one-time operation and a regular function when the logic needs more structure or reuse.
Common Mistakes: Lambda Functions
Lambda functions in Python are useful for short operations, but they have limitations. Understanding common lambda function mistakes helps you write simpler and more readable Python code.
Use the following links to jump to each mistake:
- Using Multiple Statements in a Lambda
- Forgetting That Lambda Returns One Expression
- Writing Overly Complex Lambda Expressions
- Using Lambda When
defIs Clearer
1. Using Multiple Statements in a Lambda
A lambda function can contain only one expression. You cannot place multiple statements in a lambda function.
Error: Using Multiple Statements
# Invalid
calculate = lambda x:
y = x * 2
return y
The example above is invalid because it tries to use an assignment statement and a return statement inside the lambda.
Correct: Using a Regular Function
Use a regular function when the operation needs multiple statements.
def calculate(x):
y = x * 2
return y
print(calculate(5))
# Output:
10
2. Forgetting That Lambda Returns One Expression
A lambda function automatically returns the result of its single expression. You cannot use a return statement inside a lambda.
Error: Using return in a Lambda
# Invalid
square = lambda x: return x ** 2
The example above is invalid because a lambda automatically returns the result of its expression. A separate return statement is not allowed.
Correct: Returning the Expression Result
Write the expression directly after the colon. Python automatically returns its result.
square = lambda x: x ** 2
print(square(5))
# Output:
25
Explanation: Here, x ** 2 is the single expression, so the lambda automatically returns its result.
3. Writing Overly Complex Lambda Expressions
A lambda should handle a short and simple operation. Complex expressions can make the code difficult to read and maintain.
Error: Using a Complex Lambda
# Difficult to read
result = lambda x: x * 2 if x > 10 else x + 5 if x > 5 else x - 2
print(result(12))
# Output:
24
The lambda contains multiple conditions, which makes the logic harder to understand at a glance.
Correct: Using a Regular Function
A regular function can make the same logic clearer:
def calculate(x):
if x > 10:
return x * 2
elif x > 5:
return x + 5
else:
return x - 2
print(calculate(12))
# Output:
24
When a lambda becomes difficult to read, use a regular function instead.
4. Using Lambda When def Is Clearer
A lambda is not always the best choice. A regular function is clearer when the operation needs a meaningful name, multiple steps, or repeated use.
Lambda Example
calculate_total = lambda price, tax: price + (price * tax / 100)
print(calculate_total(1000, 18))
# Output:
1180.0
The calculation is short, but a regular function can make the purpose clearer when the operation is part of a larger program.
Clearer: Using def
def calculate_total(price, tax):
tax_amount = price * tax / 100
total = price + tax_amount
return total
print(calculate_total(1000, 18))
# Output:
1180.0
Use def when a function needs a meaningful name, several steps, or clearer documentation.
Key Takeaways: Lambda Functions
Before we finish, let’s review the key points about lambda functions in Python.
- Lambda functions create small functions using the
lambdakeyword. - A lambda can accept multiple arguments but contains only one expression.
- Lambda functions return the result of their expression automatically.
- Use lambdas with functions such as
map(),filter(), andsorted(). - Use
reduce()with a lambda to combine multiple values into one result. - Use
defwhen the logic is complex, reusable, or needs a meaningful name.