NB: Lambda Functions

Introduction

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. Like def, 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)>

Assigned to a Variable

Even though they don’t get a name, they can be assigned to variables.

Here, a lambda function gets assigned to sum_two_vars.

sum_two_vars = lambda x, y: x + y
sum_two_vars(2,4)
6

Check if a value is non-negative

is_non_negative = lambda x: x >= 0
is_non_negative(-9)
False
is_non_negative(0)
True

Package first element and all data into tuple

pack_first_all = lambda x: (x[0], x)
casado = ('rice','beans','salad','plaintain','chicken') # a typical Costa Rican dish

pack_first_all(casado)
('rice', ('rice', 'beans', 'salad', 'plaintain', 'chicken'))

Check for keyword “dirty”

is_dirty = lambda txt: 'dirty' in txt
kitchen_inspection = 'dirty dishes'
is_dirty(kitchen_inspection)
True
kitchen_inspection = 'pretty clean!'
is_dirty(kitchen_inspection)
False

**pass *args for unspecified number of arguments**

(lambda *args: sum(args))(1,2,3)
6

Using Lambda

Lambda functions are often used in Pandas. We will discuss there use in more detail when we get to that topic.