(lambda x: x + 1)(2)3
Programming for Data Science
Python lambda functions are small functions that can be written on one line.
Like the one line if/else statement and comprehensions, they represent Python’s lean code writing tradition.
Lambda functions don’t need to be assigned to a variable — you can put them directly in places that expect functions the return, or expressions that evaluate to, values.
They sometimes called “anonymous” functions because they don’t have to have a name.
The general form of a lambda function is as follows:
lambda x: x + 1the first x is the argument, and the x after the colon is the body of the function.
Here we just add one to the argument.
There is no return statement; the function just returns what body of the function evaluates to.
You can call the function like this:
(lambda x: x + 1)(2)3
Note how we treat it as an expression by wrapping it in parentheses.
Since it evaluates to a function, we can use function parentheses at the end.
You can assign a lambda function to a variable.
For example, here are three lambda functions assigned to variables.
sum_two_vars = lambda x, y: x + y
is_non_negative = lambda x: x >= 0
is_dirty = lambda txt: 'dirty' in txtsum_two_vars(2, 4)6
is_non_negative(-9)False
is_dirty('dirty dishes')True
Lambda functions let us do things like this:
foo = {
    'addone': lambda x: x + 1,
    'square': lambda x: x * x,
    'invert': lambda x: 1 / x
}
bar = 5 
for f in foo:
    print(bar, f, '->', foo[f](bar))5 addone -> 6
5 square -> 25
5 invert -> 0.2
Note, you can also assign function names to variables, but of course you need to define them first.
def addone(x):
    return x + 1
def square(x):
    return x * x
def invert(x):
    return 1/x
foo2 = [add_one, square, invert]
for f in foo2:
    print(f(1))2
1
1.0
Lambda functions are often used when you need use a function only once.
Some prefer them for their ability to be part of one-liners.
Lambda functions are often used in Pandas.
We will discuss their use in more detail when we get to that topic.