Lambda functions
Lambda functions are small, anonymous functions that can be defined in a simple one-line syntax, like so:
lambda arguments : expression
For example, take the following function that returns the sum of two values:
def add_up(x, y):
return x + y
print(add_up(2, 5))
7
This function can equivalently be written using the lambda function syntax, as follows:
add_up = lambda x, y: x + y
print(add_up(2, 5))
7
Note that the main restriction of a lambda function is that it can only contain a single expression—that is, you need to be able to write the expression to return the value in a single line of code. This makes lambda functions convenient only in situations where the function is sufficiently simple such that it can be expressed in a single statement.
Exercise 56 – the first item in a list
In this exercise, you will write a lambda function, first_item
, to select the first item in a list containing cat
, dog
, and...