Skip to content
On this page

Anonymous Functions

When passing functions as arguments, sometimes it's more convenient to use anonymous functions directly instead of explicitly defining a function.

In Python, support for anonymous functions is limited. For example, to calculate ( f(x) = x^2 ) using the map() function, we can either define a function f(x) or directly pass an anonymous function:

python
>>> list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))
[1, 4, 9, 16, 25, 36, 49, 64, 81]

By comparison, the anonymous function lambda x: x * x is equivalent to:

python
def f(x):
    return x * x

The keyword lambda represents an anonymous function, with the variable x before the colon indicating the function parameter.

Anonymous functions have a restriction: they can only have a single expression. The result of this expression is returned automatically, without needing an explicit return statement.

One advantage of using anonymous functions is that, since they have no name, there is no risk of name conflicts. An anonymous function is still a function object, so it can be assigned to a variable and then called using that variable:

python
>>> f = lambda x: x * x
>>> f
<function <lambda> at 0x101c6ef28>
>>> f(5)
25

Similarly, an anonymous function can also be used as a return value:

python
def build(x, y):
    return lambda: x * x + y * y

Exercise

Refactor the following code using an anonymous function:

python
def is_odd(n):
    return n % 2 == 1

L = list(filter(is_odd, range(1, 20)))

print(L)

Solution:

python
L = list(filter(lambda n: n % 2 == 1, range(1, 20)))

print(L)

Summary

Python provides limited support for anonymous functions, making them suitable for simple scenarios.

Anonymous Functions has loaded