This notebook contains an excerpt from the Python Programming and Numerical Methods - A Guide for Engineers and Scientists, the content is also available at Berkeley Python Numerical Methods.

The copyright of the book belongs to Elsevier. We also have this interactive book online for a better learning experience. The code is released under the MIT license. If you find this content useful, please consider supporting the work on Elsevier or Amazon!

< 3.3 Nested Functions | Contents | 3.5 Functions as Arguments to Functions >

Lambda Functions

Sometimes, we don’t want to use the normal way to define a function, especially if our function is just one line. In this case, we can use anonymous function in Python, which is a function that is defined without a name. This type of functions also called labmda function, since they are defined using the labmda keyword. A typical lambda function is defined:

lambda arguments: expression

It can have any number of arguments, but with only one expression.

TRY IT! Define a labmda function, which square the in put number. And call the function with input 2 and 5.

square = lambda x: x**2


In the above lambda function, x is the argument and x**2 is the expression that gets evaluated and returned. The function itself has no name, and it returns a function object (which we will talk more in later chapter) to square. After it is defined, we can call it as a normal function. The lambda function is equivalent to:

def square(x):
    return x**2

TRY IT! Define a labmda function, which add x and y.

my_adder = lambda x, y: x + y

print(my_adder(2, 4))

Lambda functions can be useful in my cases, we will see more usage in later chapters. Here we just show a common use case for lambda function.

EXAMPLE: Sort [(1, 2), (2, 0), (4, 1)] based on the 2nd item in the tuple.

sorted([(1, 2), (2, 0), (4, 1)], key=lambda x: x[1])
[(2, 0), (4, 1), (1, 2)]

What happens? The function sorted has an argument key, where a custom key function can be supplied to customize the sort order. We use the lambda function as a shortcut for this custom key function.

< 3.3 Nested Functions | Contents | 3.5 Functions as Arguments to Functions >