In Excel, and other spreadsheet functions, there are many builtin functions. What if you want to define your own whether to convert a temperature from Fahrenheit to Celsius, or to solve a mathematical equation? In the image above, you see the syntax of a lambda expression in Excel. Microsoft advise us that we may:
Use a LAMBDA function to create custom, reusable functions and call them by a friendly name. The new function is available throughout the workbook and called like native Excel functions.
You can create a function for a commonly used formula, eliminate the need to copy and paste this formula (which can be error-prone), and effectively add your own functions to the native Excel function library. Furthermore, a LAMBDA function doesn't require VBA, macros or JavaScript, so non-programmers can also benefit from its use.
In using the lambda in Excel, the following terms are used:
parameter: A value that you want to pass to the function, such as a cell reference, string or number. You can enter up to 253 parameters. This argument is optional.
calculation: The formula you want to execute and return as the result of the function. It must be the last argument and it must return a result. This argument is required.
It is much the same in Python and other programming languages! A lambda function in Python is a small, anonymous function defined using the lambda keyword. Unlike regular functions defined with def, lambda functions are typically used for simple operations and are written in a single line.
Key Characteristics
Anonymous: No name is assigned to the function.
Single Expression: Can only contain one expression, which is evaluated and returned.
Short and Concise: Ideal for simple tasks or when passing functions as arguments.
The terminology is different but means the same thing as depicted in the graphic below:
arguments: Inputs to the function (like parameters in a regular function).
expression: A single expression (formula) that is evaluated and returned.
Lets look at some simple examples, comparing using a user defined function, and the equivalent with a lambda function.
regular function
def square(num):
return num * num
print(square(5)) # Output: 25
def adder(num1, num2):
return num1 + num2
print(adder(3, 5)) # Output: 8
def arr_adder(arr):
return sum(arr)
print(arr_adder([1, 2, 3, 4])) # Output: 10
lambda equivalent
square = lambda x: x * x
print(square(5)) # Output: 25
adder = lambda x, y: x + y
print(adder(3, 5)) # Output: 8
# using a list comprehension
arr_adder = lambda arr: sum(i for i in arr)
print(arr_adder([1, 2, 3, 4])) # Output: 10
The map() function applies a function to every item in an iterable:
numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x * x, numbers))
print(squares) # Output: [1, 4, 9, 16] # each is the square of the input list
The filter() function selects elements from an iterable based on a condition.
numbers = [1, 2, 3, 4, 5, 6]
evens = list(filter(lambda x: x % 2 == 0, numbers)) # only even numbers
print(evens) # Output: [2, 4, 6]
Lambda functions can define custom sorting keys.
pairs = [(1, 'one'), (3, 'three'), (2, 'two')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
# here the output is sorted alphabetically by the string at index 1
print(sorted_pairs) # Output: [(1, 'one'), (3, 'three'), (2, 'two')]
When you need a simple function for a short task.
When passing a function as an argument to higher-order functions like map(), filter(), or sorted().
When you want concise code for one-off operations.
Limitations
Lambda functions can only contain a single expression.
They are less readable for complex logic compared to named functions.
Not suitable for functions requiring multiple statements or documentation.
For a Deep Dive, check out the realpython tutorial!
Try these exercises to practice lambda functions.
Exercise 1: Basic Lambda
Create a lambda function that takes two arguments and returns their product. Test it with inputs 4 and 5.
Exercise 2: Using with map()
Given a list [10, 20, 30, 40], use a lambda function with map() to create a new list where each element is divided by 10.
Exercise 3: Using with filter()
Given a list [1, 2, 3, 4, 5, 6, 7, 8], use a lambda function with filter() to create a new list containing only numbers greater than 5.
Exercise 4: Using with sorted()
Given a list of tuples [('apple', 3), ('banana', 1), ('cherry', 2)], sort the list by the second element of each tuple using a lambda function.
Here are the solutions- Try solving them yourself before checking!
product = lambda x, y: x * y
print(product(4, 5)) # Output: 20
numbers = [10, 20, 30, 40]
result = list(map(lambda x: x / 10, numbers))
print(result) # Output: [1.0, 2.0, 3.0, 4.0]
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
result = list(filter(lambda x: x > 5, numbers))
print(result) # Output: [6, 7, 8]
fruits = [('apple', 3), ('banana', 1), ('cherry', 2)]
sorted_fruits = sorted(fruits, key=lambda x: x[1])
print(sorted_fruits) # Output: [('banana', 1), ('cherry', 2), ('apple', 3)]
Lambda functions are concise, anonymous functions for simple tasks.
They are powerful when used with functions like map(), filter(), and sorted().
Use them sparingly for clarity, and prefer named functions for complex logic.
Python Documentation: Lambda Expressions
Practice more with online platforms like LeetCode or HackerRank.