Python lambda expressions

Lambda expressions – also called “anonymous functions”.

Lambda expression #

Simple function:

def f(x):
    return 2*x

f(2)
# 4

As a lambda expression:

lambda x: 2*x

We can assign it to a variable:

g = lambda x: 2*x

g(2)
# 4

Multiple inputs #

lambda x, y, z: <expression including x, y, z>

example:

full_name = lambda first_name, last_name: first_name.strip().title() + " " + last_name.strip().title()

full_name(" John", "smith ")
# John Smith

Reminder: strip() removes trailing white spaces, title() capitalizes

Lambda on a list #

Lambda functions can be applied to entire lists.

List functions sometimes have a key argument that can be populated with a lambda expression.

example:

list_of_full_names = [...]

# sort by surname
list_of_ful_names.sort(key = lambda name: name.split(" ")[-1])

Function to make functions #

# example from Socratica

def build_quadratic_function(a, b, c):
    """
    return function f(x) = ax^2 + bx + c
    """
    return lambda x: a*x**2 + b*x + c

f = build_quadratic_function(2, 3, -5)

f(0)
# -5

f(1)
# 0

# without naming the function
build_quadratic_function(2, 3, -5)(0)
# -5