example of a lambda function

#How to define and use lambda functions

add = lambda a, b: a + b

print(add(6, 9))

In Python, a Lambda Function is a single-lined function that is defined without an explicit name. They are also known as anonymous functions.

While the def keyword is used to define named functions, the lambda keyword is used to define anonymous functions i.e lambda functions.

The lambda functions are more lightweight and concise compared to named functions, this makes them ideal for simple operations that do not require complex logic.

To define this type of functions, we use lambda keyword with arguments and the expression as shown below:

lambda arguments : expression

The comma-separated arbitrary arguments are separated from the function expression/body by a colon.  We can only use one expression in the functions body.

Note: lambda functions can have any number of arguments but only a single expression.

Consider the following function:

def func(x): 
    return x

The equivalent lambda function to the above function is as follows:

lambda x : x

We do not need to explicitly use the return statement with lambda functions because it automatically returns the value of the expression after evaluation. Other examples:

a lambda function to add two numbers:

lambda a, b : a + b

The above lambda function takes two arguments  a and b and returns the sum of those two arguments (a + b).

a lambda function to tell whether a number is  odd or even:

lambda num : "Odd" if num % 2 else "Even"

The above lambda function will return 'Odd' if the number is odd , else it will return 'Even'.

Calling lambda functions

A lambda functions can be called  directly by enclosing it with parentheses, For example:

#returns the input value
print((lambda x : x)(9))

#returns the sum of the two arguments
print((lambda a, b : a + b)(10, 20))

#Checks whether a number is even or odd
print((lambda x : 'Odd' if x % 2 else 'Even')(50))

However, in order to make the lambda functions persist and be usable multiple times, we  can assign them to a variable,  then use the variable name to call the function. Example:

add = lambda a, b : "%s + %s = %s"%(a, b, a + b)
print(add(1, 2))
print(add(6, 7))
print(add(100, 200))

This is not unique to lambda functions, we can also assign variable names to normal functions, however, the normal function retains it's declaration name because the name is associated with the function object itself.

def add(a, b):
    return a + b

demo = add
print(demo(1, 2))
print(demo(100, 200))

#The function retains declaration name

Uses of lambda functions

Lambda functions are in some cases more cryptic than the 'normal' functions because you have to compress all the function logic into one expression. Additionally,  anything that you can  achieve with lambda functions, you can also effectively accomplish it with the named functions. There are some instances, however, when lambda functions are more suitable than named functions.

For simple transformation

The lambda functions can be more suitable if all we want is to transform an object in a simple way. Examples:

x = 5
y = 10
print(x + (lambda a : a *a)(y) ) #print sum of x and the square of y
my_list = [8, 7, 2, 9, 5]
print((lambda l : sorted(l))(my_list)[0]) #get the first element of the sorted a sorted list.

As arguments to higher-order functions

In Python and other functional languages, it is common to pass functions as arguments to other functions. In such cases, lambda functions are often used because they can be defined inline. Some builtin such functions includes:

The map() functions:

Used to perform an action on each item in a sequence


L = list(map(lambda a : a + 1,[10, 20, 30, 40]))  # add 1 to each number in a list
//[11, 21, 31, 41]
names = [('John', 'Doe'), ('Jane', 'Doe'), ('Will', 'Smith')] # return a fullname given a tuples of first and last names
names = list(map(lambda name: name[0] + ' ' + name[1], names ))
//['John Doe', 'Jane Doe', 'Will Smith']
The filter() functions:

Used to filter values in given sequence by their boolean values, based on a given function. Examples:

my_list = [1, 5, 3, 11, 0, 2, 9, 4, 15,8, 10, 35, 67, 25, 30]
evens = list(filter(lambda a: not a % 2, my_list)) #return only the even numbers in my_list
//[0, 2, 4, 8, 10, 30]
multiples_of_5 = list(filter(lambda a: a and not a % 5, my_list)) #returns only the multiples of 5 in my_list
//[5, 15, 10, 35, 25, 30]
The functools.reduce() function:

Applies a function of two arguments cumulatively on a sequence of elements from left to right, reducing the sequence to a single value.


from functools import reduce
my_list = [1, 2, 3, 4, 5]
sum = reduce(lambda a, b : a + b, my_list)#returns the sum of all the numbers in my_list
prod = reduce(lambda a, b : a * b, my_list) #returns the product of all the numbers in my_list

As key Functions

Lambda expressions can be used as keys in functions and methods that allow customization using functions as keys. For example in the builtin sorted() function and the sort() method of lists, a lambda expression can be used to define the sorting criteria, for example:

my_list = [('John', 30), ('Joe', 20), ('Jane', 25)] 
my_list = sorted(my_list, key = lambda a : a[1] )
//[('Joe', 20), ('Jane', 25), ('John', 30)]

In the above example, we use the lambda expression to indicate to the sorted() function that it should sort the list elements(which are tuples) based on their second elements(at index 1). If no key was given the function would have sorted the list element alphabetically, based on their first element, therefore, the sorted list would have been [('Jane', 25), ' ('John', 30), ('Joe', 20)].

Other builtin functions that allows key argument includes max() and min() For example:

data = [{'name': 'John', 'age': 30 }, {'name': 'Alex', 'age': 24}, {'name': 'Sam', 'age': 28}]
max_age = max(data, key=lambda x:x['age'])
min_age = min(data, key=lambda x:x['age'])
print("The oldest person is", max_age['name'])
//The oldest person is John
print("The youngest person is", min_age['name'])
//The youngest person is Alex