lambda x: x
<function __main__.<lambda>(x)>
Python lambda functions are small, informal functions. They don’t get a name.
The are “anonymous.”
From Lutz 2019:
Besides the
def
statement, Python also provides an expression form that generates function objects. Because of its similarity to a tool in the Lisp language, it’s called lambda. Likedef
, this expression creates a function to be called later, but it returns the function instead of assigning it to a name. This is why lambdas are sometimes known as anonymous (i.e., unnamed) functions. In practice, they are often used as a way to inline a function definition, or to defer execution of a piece of code.
The general form of a lambda function is:
lambda x: x
<function __main__.<lambda>(x)>
You can call the function like this:
lambda x: x)(2) (
2
increment x
lambda x: x+1)(5) (
6
sum two variables
lambda x, y: x + y
<function __main__.<lambda>(x, y)>
Even though they don’t get a name, they can be assigned to variables.
Here, a lambda function gets assigned to sum_two_vars
.
= lambda x, y: x + y sum_two_vars
2,4) sum_two_vars(
6
Check if a value is non-negative
= lambda x: x >= 0 is_non_negative
-9) is_non_negative(
False
0) is_non_negative(
True
Package first element and all data into tuple
= lambda x: (x[0], x) pack_first_all
= ('rice','beans','salad','plaintain','chicken') # a typical Costa Rican dish
casado
pack_first_all(casado)
('rice', ('rice', 'beans', 'salad', 'plaintain', 'chicken'))
Check for keyword “dirty”
= lambda txt: 'dirty' in txt is_dirty
= 'dirty dishes'
kitchen_inspection is_dirty(kitchen_inspection)
True
= 'pretty clean!'
kitchen_inspection is_dirty(kitchen_inspection)
False
**pass *args for unspecified number of arguments**
lambda *args: sum(args))(1,2,3) (
6
Lambda functions are often used in Pandas. We will discuss there use in more detail when we get to that topic.