avatarDevTechie

Summarize

Python — lambda functions

Python — lambda functions

We have already discussed functions which can be created using the def keyword. Python also has an elegant way to write on-the-fly functions called lambda functions. The article elaborates on ‌lambda functions.

What is a lambda function?

A lambda function is a small (usually a single line of code ) function. In Python, lambda functions can take any number of arguments but only have a single expression.

A lambda function is defined using the lambda keyword followed by the arguments and the expression. The syntax for lambda functions is as shown below

lambda arguments: expression

The syntax shows that a lambda function does not have a name.

In the syntax, arguments refer to parameters, and finally, the single expression depicts the function body.

lambda functions are also called anonymous functions.

Lambda functions are handy when you need to define a function quickly and don’t want to go through the process of defining a named function using the def keyword. They are also useful when we need to pass a function as an argument to another function.

Defining a lambda function includes three elements:

  • The keyword lambda — analogous to def in normal function.
  • The parameters/arguments — also support passing positional and keyword arguments, just like normal functions
  • The body — the single line expression being evaluated with the lambda function

Unlike a normal function, you don’t have to use parenthesis to enclose the parameters of a lambda function. You cna use comma to seperate parameters if the lambda function takes more than one parameter.

Why lambda functions?

Advantages of lambda functions include:

1 — Concise code

Lambda functions allow us to write concise code by reducing the number of lines of code required to define a function.

2 — No need to define a named function

Lambda functions do not require us to define a named function, which can be useful when we only need to 3 — use a function once.

3 — Can be used as an argument to another function

Lambda functions can be used as an argument to another function, which can make our code more modular and concise.

Why not lambda functions?

Disadvantages of lambda functions include:

1 — Difficult to understand

Lambda functions can be difficult to understand, especially for beginners who are not familiar with the syntax.

2 — Reduced readability

Lambda functions can reduce the readability of our code, especially if they are used excessively.

3 — Reduced performance

Lambda functions can be slower than named functions, especially if they are used in a loop.

The examples

Example 1

Consider that you have to write a function which returns the cube of a number.

Using the normal function approach, it can be defined as shown below

def cube(n):
    c= n * n * n
    return c

Using the lambda function approach, we can define the same function in a single line as shown below:

cube = lambda n : n * n * n

You can use this lambda as follows:

print(cube(4))

The output will be

64

The above lambda function, takes one argument denoted by n and returns its cube. Lambda functions can have as many numbers of arguments as you want but can have only one expression.

Example 2

Let’s creates a lambda function which can take two arguments

# labmda function is one liner function
minus = lambda x,y: x-y
# use the function
print(minus(18,7))

The output will be

11

Example 3

The below function takes three arguments

# lambda function can take any no of parameters but has only one expression
x = lambda a,b,c,d: a+b+c+d
# use the function
print ("x =", x(1,11,22,3))

The output will be

x = 37

A practical use of lambda function

You all know that, in Python, you can use the sort() method to sort a list (by default ascending). In Python, the sort() method has a key parameter.

The key parameter is used to specify a function that is called on each element of the list before sorting. The value returned by the function is used to determine the order of the elements in the sorted list. Here comes the role of lambda functions.

The below code is an example of using the key parameter to sort a list of records (here inner lists but tuple etc. can also be used) based on the second element of each record. The code defines a lambda function on the fly.

list1=[[1,23],[4,56],[23,3]]
# below x refers to the inner lists received as parameter e.g. [4,56]
# here sorting is done by comparing second element of all three inner lists
# trying changing x[1] to x[0]
list1.sort (key = lambda x: x[1]) 
print (list1)

In the code, the lambda function lambda x: x[1] is used as the key . The key function takes each inner-list in the list and returns the second element of the inner-list (record). The sort() method then uses these values to sort the list in ascending order based on the second element of each inner-list.

The output of the above code is

[[23, 3], [1, 23], [4, 56]]

If you change x[1] to x[0] in the above code, the output will be

[[1, 23], [4, 56], [23, 3]]

In real life applications, the inner-list refers to a record and the outer-list refers to the bunch of records, this kind of sorting will be very valuable.

Arbitrary arguments to lambda function

# define arbitrary no of arguments 
z = lambda *l1: sum(l1)
print(z(*[34,67]))

The output will be

102

Arbitrary keyword arguments in lambda function

# arbitrary number of keyword arguments 
k=lambda **kwargs: sum(kwargs.values())
#using the above function
print ( k (one=1, two=2, three=3) )
# The above two lines of code can be combined into a single one
print((lambda **kwargs: sum(kwargs.values()))(one=1, two=2, three=3))

The output is:

6

Recapitulate

This article talks about the lambda function which is a small anonymous function in Python that can take any number of arguments but can only have one expression.

With that we have reached the end of this article. Thank you once again for reading. If you liked this, don’t forget to 👏 and follow 😍. Also visit us at https://www.devtechie.com

Python
Data Science
Machine Learning
Programming
Devtechie
Recommended from ReadMedium