Lambda functions are very convenient for performing simple operations that do not require complex logic. The entire lambda function is defined in a single line including the declaration and body.

Unlike traditional functions, lambda functions do not have a name, thus they are also referred to as anonymous functions.

Basically lambda functions are made up of three parts:

  • The lambda keyword.
  • Arguments separated with a comma.
  • A single expression.

The following is the syntax of lambda functions:

lambda arg1, arg2 : expression

The comma separated arguments can be as many as necessary, they are separated from the expression by a colon(:). The expression can be seen as the body of the function, it is where the main logic goes. A lambda function can only have a single expression, it can be any valid expression.

With lambda functions, we do not need to explicitly use the return statement, this is because the result of the expression is returned automatically after it is evaluated.

In the following parts we will check on various  ways we can use and apply lambda functions.

A lambda function without arguments

A lambda function can be defined without any arguments, however the expression must be present for a lambda function to be valid.

In the following snippet we define a lambda function without arguments, when called the function  simply prints "Hello, World!" to the console. 

func = lambda : print('Hello, World')

#call the function
func()

The arguments section of the above function is empty because the function does not take any arguments.  The expression is simply a print statement for printing "Hello, World" to the console.

Note that we assigned the function to a variable i.e func, this allows us to reference the function as it does not have its own declaration name.

The "normal" function that is equivalent to the above lambda function is shown below.

def func():
   print('Hello, World')

#call the function
func()

A lambda function to square a number

A lambda function to square a number takes in a single argument which is the number to be squared.

square = lambda a : a ** 2

print(square(5))
print(square(12))
print(square(20))

In the above example, we defined a lambda function and assigned it to the variable square.  The function takes in a as the argument and returns its square.

As earlier mentioned, we do not need to use the return keyword because lambda function automatically returns the result after evaluating the expression.

A lambda function to add two numbers

The function takes the two numbers as the arguments and then returns their sum

add = lambda a, b : a + b

print(add(10, 20))
print(add(30, 40))

We can make the output to be visually appealing by using a formatted string as the output, as shown below:

add = lambda a, b : f"{a} + {b} = {a + b}"

print(add(10, 20))
print(add(30, 40))

The f before strings is used for making f-strings(formatted strings). f-strings allow us to use variables and expression in the strings, the expression inside the curly braces  are first evaluated before the string is formed.

A lambda function with default arguments

Like in normal functions, we can define a lambda function with default arguments. The default arguments are only used if they are not replaced when the function is called.

In the following snippet, we define a lambda function that takes two arguments a, and b . The function returns the result of raising a to the power of b. b defaults to 2 so that if another value is not given, the square of a will be returned.

power = lambda a, b = 2 : a ** b

print(power(4))
print(power(5))
print(power(10, 3)) #use non-default

A lambda function with arbitrary arguments

We use function with arbitrary arguments where we do not know in advance how many arguments may be entered. In both traditional and lambda functions, arbitrary arguments are defined with either single or double asterisks depending on whether they are  positional or keyword arguments.

A single asterisk(*) is used to represent arbitrary positional arguments. *args is normally used for arbitrary positional arguments. Consider the following example.

add = lambda *args : sum(args)

print(add(3, 4))
print(add(1, 2, 3, 4))
print(add(20, 40, 60))

We defined a lambda function for calculating the sum of the values entered as argument. The number of the values is not known in advance and hence we used the arbitrary positional argument.

The positional arguments are received in the body/expression as a tuple.

On the other hand, double asterisks(**) are used to represent arbitrary keyword arguments. **kwargs is normally used for the keyword arguments. The arguments are received in the body/expression as a dictionary. consider the following example.

func = lambda **kwargs : kwargs

print(func(a = 10, b = 20, c = 30))

As shown above the kwargs parameter evaluates to a dictionary and we can therefore perform all valid dictionary operations on them.

We can also combine the two types of arbitrary arguments (*args and **kwargs) in the same function. The positional arguments are received as a tuple while the keyword arguments are received as a dictionary.

func = lambda *args, **kwargs : print(f"args: {args}", f"kwargs: {kwargs}", sep = '\n')

func(1, 2, 3, x = 10, y = 20, z = 30)

Lambda Function with map()

The map() function applies a given function to the elements of an iterable object. It has the following syntax:

map(function, iterable)

It applies the function to each element of the iterable and then returns an iterator object which yields the transformed values.

Due to their concise syntax and ability to be defined in-line, lambda functions are normally used in map(). For example consider if we want to square each value in a list of integers we can do it as follows:

nums = [3, 4, 5, 6]

transformed = list(map(lambda x : x **2 , nums))

print(transformed)

By using lambda x : x ** 2 as the first argument to the map() function we are able to square each value in the list nums. We used the list() function to create a list from the returned iterator.

In the following example, each string in a list of strings is  uppercased.

my_list = ['python', 'java', 'php', 'Javascript']

transformed = list(map(lambda x : x.upper(), my_list))

print(transformed)

In the above case, we are able to transform all strings to uppercase by using the map() function with lambda x : x.upper() as the function argument.

Lambda function with filter()

The filter() function filters the elements of an iterable based on a boolean function that is given as its argument.

filter(function, iterable)

The function is supposed to take a single argument and return either True or False. filter() returns an iterator which yields only those elements that evaluated to True.

In the following example, we use the filter() function to get only the even numbers while ignoring the odds

nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

result = list(filter(lambda x : x % 2 == 0, nums ))

print(result)