Functions in Python usually have names, but sometimes you need a small function that you only need to use once. These are called lambda functions or lambda expressions.
They are most often used when you want to pass a function to another function. This is possible because functions, like most things in Python, are objects. You can pass them around or store them in containers, just like other objects.
In this code, we assign a lambda (anonymous, un-named) function to a variable, then call it using the variable. This is usually not a good idea; if you want to refer to a function by name, create a normal function; but it does illustrate well how lambdas work.
The parameters are specified after the lambda keyword, before the colon. After that we specify an expression (something that can be evaluated to a simple value), and that becomes the return value.
func = lambda x: x**2 print(func(4))
Passing a Function to a Function
A more typical use of a lambda expression is to pass it to a function.
Here we pass a lambda function that just multiplies its input by 3. The calculate function then applies it to the value that’s also been passed.
def calculate(func, value): return func(value) result = calculate(lambda x: 3 * x, 9) print(result)
Typical Lambda Use: Sorting Strings
A more typical use of a lambda expression is to sort strings.
Here we use a lambda function to sort strings in order of their length.
The list sort method has a parameter called key, which allows us to supply a function that specifies how the list should be sorted. We pass it a lambda function that accepts a string in its s parameter. It returns the length of the string, using the len builtin function. The sort method then sorts the strings in numerical order of whatever len returns.
strings = ["cat", "orange", "fantastic", "it"] strings.sort(key=lambda s: len(s)) print(strings)
['it', 'cat', 'orange', 'fantastic']
Here’s how the same thing would look if we just used a normal function instead.
def sort_strings(s): return len(s) strings = ["cat", "orange", "fantastic", "it"] strings.sort(key=sort_strings) print(strings)
Using a lambda for a small task like this saves some typing.
To pass a function to another function or to assign the function to a variable, use only the name of the function.
When we use round brackets after the function name, like calculate() for example, we actually call the function (make it actually run).