Lambdas

https://docs.python.org/3/reference/expressions.html#lambda

INTRODUCTION

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. Functions created with lambda expressions cannot contain statements or annotations.


# Syntax.

lambda arguments: expression   # yields a function object

# The unnamed object behaves like a function object defined with:

def <lambda>(arguments):
    return expression

sum_items = lambda x, y, z: x + y + z
print(sum_items(2, 3, 4))   # 9

def sum_items(x, y, z):   # the same result
    return x + y + z

# Default arguments.

sum_items = lambda x=0, y=0, z=0: x + y + z
print(sum_items())   # 0
print(sum_items(6, 7))   # 13

# C++ vs Python.
auto pr = [] (int& n) { std::cout << n << ' '; };
for (auto& n : {0, 1, 2, 3, 4}) { pr(n); }

pr = lambda n: print(n, '', end='')
for n in range(5): pr(n)

CUSTOM SORTING


number_list.sort(reverse=True)
number_list.sort(key=lambda x: -x)   # the same

L = [(2, "gamma"), (-7, "alpha"), (4, "beta"), (4, "delta")]   # a list of records

L.sort(key=lambda t: (-t[0], len(t[1])))
# t[0] decreasing, for the same t[0] use the length of t[1]
# [(4, 'beta'), (4, 'delta'), (2, 'gamma'), (-7, 'alpha')]

L.sort(key=lambda t: (t[1], abs(t[0])))
# t[1] increasing (lexicographic order), for the same t[1] use abs(t[0])
# [(-7, 'alpha'), (4, 'beta'), (4, 'delta'), (2, 'gamma')]

ACTIONS


def show_sequence(sequence, action=None):
    for item in sequence:
        print(item)
        if action:
            action(item)

show_sequence([1, 2, 3, 4], action=lambda x: print(x*x))   # Py3

M = []
show_sequence([1, 2, 3, 4], action=lambda x: M.append(x*x))

# Example: BFS or DFS in graphs.

EXERCISES


Define the following functions using lambda: abs(x), min(x, y), max(x, y).