from IPython.core.display import HTML

HTML(open("custom.html", "r").read())
Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

Copyright (C) 2014-2023 Scientific IT Services of ETH Zurich,
Contributing Authors: Uwe Schmitt, Mikolaj Rybniski

13. Anonymous, aka "lambda" functions¶

Functions can be created as objects using lambda.

Syntax is lambda <ARGS>: <EXPRESSION>:

f = lambda x: x * x
print(f(2))
4
g = lambda: 7

print(g())
7

Such lambda functions do not accept statements like if or for and are as such not as versatile as functions declared with def.

Typical use case is to construct a simple function on the fly when used as a function argument. Drawback is that lambda expressions don't carry a name which might affect readability:

def numbers(n, filter_function):
    return [i for i in range(n) if filter_function(i)]


print(numbers(10, lambda n: n < 5))
print(numbers(10, lambda n: n % 3 == 1))
[0, 1, 2, 3, 4]
[1, 4, 7]

Exercise section¶

Play the the examples.

Optional exercise*¶

Modify the existing solution for sorting a list of strings ignoring their case such that you use a lambda function for the key argument of sort.