Chapter 5: Lambda functions

Lambda functions

face Josiah Wang

We will now briefly explore yet another programming paradigm. This one is called functional programming.

Don’t worry, we won’t go into too much detail on the topic, as these features are not an essential part of Python. These are just for your additional knowledge.

Functional programming is a paradigm where you define your programs by composing and applying functions, rather than a sequence of instructions. Haskell is an example of a functional programming language. For example, such languages use recursion instead of loops to achieve iteration.

Python does not provide full functional programming capabilities, but some functional programming features did manage to sneak into Python!

One example of these is lambda functions.

Lambda functions, simply put, are functions with no name. They are also known as anonymous functions.

So, instead of writing something like this:

def add(x, y, z):
    return x + y + z

print(add(1, 2, 3))

You can technically do something like this.

output = (lambda x, y, z: x+y+z)(1, 2, 3)
print(output)

For clarity, the above code could be rewritten as follows. Note that the code below is purely for illustration. PEP 8 explicitly discourages this because it makes your code less readable. Just define your functions using def!

add = lambda x, y, z: x+y+z
print(add(1, 2, 3))

Lambda functions can only have one expression in its body (x+y+z above). You cannot have statements in its body (e.g. return, assert, raise). Remember that x+y+z is an expression, not a statement!

The mathematicians among you might be familiar with lambda calculus, which is where lambda functions come from.

In Python, there is a time and place to use lambda functions, so you should not go crazy and start replacing all your functions with lambda functions.

”… the only advantage of using a lambda instead of a locally-defined function is that you don’t need to invent a name for the function … ” [source]

In general, if using lambda functions makes your code hard to read, then don’t use it!

In this and the next chapter, we will look at times when lambda functions can actually useful.