Lambda Me This…
If you’re new to programming like me you’ll probably find that as you continue to dive deeper into any language and look at Stack Overflow and other resources to try to help you solve problems, you discover new code that you’ve never seen before. During my journey to learn python I stumbled across something called lambda. Your first thought when you see the world lambda may take you down a rabbit hole of Greek mythology, or pull you over into the physics world. But when it comes to python, lambda is actually a shorthand tool we can use to write functions. Let’s big a little deeper into understanding how lambda works in the python world.
What is a lambda function?
In python we traditionally define a function by first using the def keyword, followed by the name of the function, then the paramenter for the function in parenthesis, a colon, and finally the body of the function indented in on the next lines down:
def sum(a, b):
return a + b
print(sum(3,5))
#LOG: 8However, for very simple functions, like the one above, this can be a lot of extra code. Thankfully python gives us an alternative way to write functions using lambda. Lambda functions are anonymous functions that provide a shorthand syntax for creating functions in python.
Lets Write Lambda Functions
The syntax for a lambda function is the lambda keyword, followed by the the arguments, a colon, and finally an expression:
# Syntax: lambda arguments : expression
lambda x : x * 2There's a few things to note about lambda functions:
- These functions can take any number of arguments
- They can only have ONE expression, which is evaluated and returned
Invoking Anonymous Functions
As we mentioned earlier, lambda functions are anonymous functions, which means they don’t have a name associated with them. And without a name, we can’t invoke a function. So what do we do? One thing you can do is assign a lambda funciton to a variable.
Assigning Lambda Functions to Variables
Lets take a look a assigning a lambda to an variable, reusing our lambda syntax and sum function examples from earlier:
multiply = lambda x : x * 2
sum = lambda a, b : a + b
print(multiply(5))
#LOG: 10
print(sum(3,5))
#LOG: 8
If we take a look at the multiply funciton, we are able to invoke the lambda function using the tradition method of invoke a function (parenthesis ()) and passing a single argument to the variable name it was assigned to. If we look at the sum function, we are able to pass multiple paramenters to a lambda function. This same function that took us two lines using the traditional python function declaration method only took us one line using a lambda function.
Other Uses for Lambda Functions
Lambda and Callback Functions
Callbacks functions are functions that are passed as arguments to other functions or invoked within another function. And a lot of the time callback functions are anonymous functions. You can pass a lambda function as a callback to another function. The lambda function can be defined inline as well. Lets take a look at these examples below:
Map() and Filter()
The map and filter functions in python take two arguments, a function an iterable. The function passed to map and filter is run on every element in the iterable and is passed the current element as an argument. In other words, the map and filter functions call the passed in function on each element and passes the element as an argument, making the passed in function a callback function. They both return a filter or array object that you can iterate over. The objects will contain the modified elements based on the conditions in the callback function. That callback function used in map and filter can be a lambda function.
# map(func, iterable)
# filter(func, interable)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
double_nums = map(lambda num: num*2, numbers)
print(list(double_nums))
# LOG: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
is_even = filter(lambda num: num % 2 == 0, numbers)
print(list(is_even))
# LOG: [2, 4, 6, 8, 10]Here we pass an anonymous, inline lambda function as the first parameter to the map and filter functions. The second paramenter is the iterable which is the list numbers. Map and filter pass each element of the iterable to the callback as an argument. The map function uses the lambda callback function to double each element in the list. The filter function uses the lambda callback function to check to see if a number is even or not.
Sorted()
The sorted function by default sorts an iterable alphabetically.
cars = ["Ford", "Honda", "BMW", "Mercedes", "VW"]
x = sorted(cars)
print(x)
#LOG: ['BMW', 'Ford', 'Honda', 'Mercedes', 'VW']However, sorted takes an optional second argument, key, which is set equal to a function to execute to decide what to sort by. This key argument can be set equal to a lambda function:
cars = ["Ford", "Honda", "BMW", "Mercedes", "VW"]
x = sorted(cars, key = lambda x : len(x))
print(x)
#LOG: ['VW', 'BMW', 'Ford', 'Honda', 'Mercedes']Here we set key equal to an anonymous inline lambda function to gets the length of each element in the list. The sort function uses the lambda callback function to sort the list by length.
Lambda and if-else
We can use lambda functions with ternary expressions to create simple if-else functions:
max_num = lambda a, b : a if a > b else b
print(max_num(3,5))
#LOG: 5We can use a ternary expression to compare the arguments passed to the lambda function and return whichever number is bigger.
Conclusion
Lambda functions are a great tool in python when you need to write a simple, single line functions usually involving short operations. They can be easily passed as callback functions and defined inline so that you don’t have to clog the global scope with a function that only needs to be used once. However if you need to write a multi-line function or need to explain parts of you function, you should probably us the standard python function definition.
Aside: Do lambda functions remind you of anything? If you’ve dabbled at all in JavaScript, you may be familiar with arrow functions. Arrow functions are by definition anonymous functions and can be assigned to a variable as well. They are also often passed as callbacks and used in other similar situations as lambda functions. And if you look at the syntax of a python lambda function vs a JavaScript arrow function, you might see some similarities there are well!
Reference List
[1] “Python lambda functions,” GeeksforGeeks, https://www.geeksforgeeks.org/python-lambda-anonymous-functions-filter-map-reduce/ (accessed Sep. 21, 2023).
Get Kimberly Love’s stories in your inbox
Join Medium for free to get updates from this writer.
[2] T. A. Dorfer, “How to effectively use lambda functions in python as a data scientist,” Medium, https://towardsdatascience.com/how-to-effectively-use-lambda-functions-in-python-as-a-data-scientist-fd6171554053 (accessed Sep. 21, 2023).







