One last type of functions that I want to talk about are anonymous functions. These functions, which are called lambdas in Python, are usually used when a fully-fledged function with its own name would be overkill, and all we want is a quick, simple one-liner that does the job.
Imagine that you want a list of all the numbers up to N which are multiples of five. Imagine that you want to filter those out using the filter
function, which takes a function and an iterable and constructs a filter object which you can iterate on, from those elements of iterable for which the function returns True
. Without using an anonymous function, you would do something like this:
filter.regular.py
def is_multiple_of_five(n):
return not n % 5
def get_multiples_of_five(n):
return list(filter(is_multiple_of_five, range(n)))
print(get_multiples_of_five(50))
I have highlighted the main logic of get_multiples_of_five
. Note how the filter uses is_multiple_of_five
to filter the first n natural numbers. This seems a bit excessive, the task is simple and we don't need to keep the is_multiple_of_five
function around for anything else. Let's rewrite it using a lambda function:
filter.lambda.py
def get_multiples_of_five(n):
return list(filter(lambda k: not k % 5, range(n)))
print(get_multiples_of_five(50))
The logic is exactly the same but the filtering function is now a lambda. Defining a lambda is very easy and follows this form: func_name = lambda [parameter_list]: expression
. A function object is returned, which is equivalent to this: def func_name([parameter_list]): return expression
.
Let's look at another couple of examples of equivalent functions defined in the two forms:
lambda.explained.py
# example 1: adder def adder(a, b): return a + b # is equivalent to: adder_lambda = lambda a, b: a + b # example 2: to uppercase def to_upper(s): return s.upper() # is equivalent to: to_upper_lambda = lambda s: s.upper()
The preceding examples are very simple. The first one adds two numbers, and the second one produces the uppercase version of a string. Note that I assigned what is returned by the lambda
expressions to a name (adder_lambda
, to_upper_lambda
), but there is no need for that when you use lambdas in the way we did in the filter
example before.