The Wonderful World of Python Lambdas

Lambda ($\lambda$) expressions, also called anonymous functions, are a staple of functional programming. But did you know the following fun facts about them?

They don’t need to be anonymous. They can be used to quickly create a one-line function which can be stored in a variable:

squareit = lambda x: x**2
> 16

They are not functions, but expressions, hence they can be passed as arguments to other functions:

mylist = [2,4,6,8]
print(list(map(lambda x: x+1, mylist)))
> [3, 5, 7, 9]

Lambdas can be called directly:

print((lambda x, y: x**2 + y**2)(2,3))
> 13

They can also be called recursively!

factorial = lambda x: 1 if x==0 else x*factorial(x-1)
> 3628800

Lambdas can be used as for evaluating whether a statement is True or False and chained together using Python’s rules for chaining logical operators:

is_even = lambda x: x%2 == 0
is_number = lambda x: isinstance(x, (float, int))
is_even_number = lambda x: is_even(x) and is_number(x)

> True

> False

This can be used for control flow:

#continuing from above

is_even_number_verbose = lambda x: is_even_number(x) or \
                         print(f"{x} is either not 
                               even or not a number")

> True

> 5 is not even or is not a number

Expressions can be chained inside lambdas using ternary operators (but don’t overdo it like in this example!):

how_large = lambda x: "Small" if (x<0 or x<10) \
                       else "Medium" if (x>=10 and x<100) \
                       else "Large"

> Small

> Large
Georgios Kaissis
Georgios Kaissis
Specialist Diagnostic Radiologist - Senior Research Scientist

My research interests include AI-based medical image analysis, probabilistic methods and privacy-preserving AI