×

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python.

Python lambda functions are anonymous functions. It means that a function is without a name. Any function in python is defined using the ‘def’ keyword. Similarly, a lambda function is defined using a ‘lambda’ keyword for defining the anonymous functions.

Syntax

The syntax for creating a lambda function is:

lambda arguments: expression

Properties

  • Python lambda function can have any number of arguments, but it will only have one expression. That expression is later on evaluated and returned.
  • Anyone can use the lambda function whenever an object function is required.
  • We should always remember that lambda functions are syntactically restricted to one expression only.

Example of Lambda Function

Let’s understand with an example of the lambda function.

# Program to show the use of lambda functions
double = lambda x: x * 10


print(double(2))

Output

20

Explanation

In the above program, we have used the lambda function using the lambda keyword and an expression. lambda x: x*10 is a lambda function. In this lambda function, x is the argument, and  x*10 is an expression. This expression is evaluated and returned. The function has no name and returns a function object assigned to the identifier double.  We can call it a normal function.

double = lambda x: x * 10

can also be written as

def double(x):
    return x * 10;

Difference between Lambda function and def function

Using an example, let’s understand the difference between the lambda function and a def function. This program will return the square of a number.

Code:

def  square(y):
    return y*y
  
lambda_square = lambda y: y*y
  
# using the normally
# defined function
print(square(5))
  
# using the lambda function
print(lambda_square(5))

Output

25
25

Explanation

As you can see, both functions square() and lambda_square()are doing the same thing. They both give an output of the square of the numbers passed as argument. When we use a function, we have to pass a value to the function defined using the def keyword. In this function, we have to give a name to the function. After evaluating the value, we can return the value to where the function was called using the return keyword.

While we use the lambda function, we don’t have to use the return statement. It always returns an evaluated and returned expression without using any return keyword. We can also put the lambda expression anywhere in the code, and we don’t have to assign it to a variable. This is how we can use a lambda function.

Using of Lambda function with list comprehension

y = [lambda x=x: x*2 for x in range(1, 11)]
  
for table in y:
    print(table())

Output

2
4
6
8
10
12
14
16
18
20

Explanation

In the above code, we have used the lambda function with a list comprehension. This program will print the table of two from range 1 to 10. In this program, we have used x as an argument and x*2 as an expression. This expression will get evaluated and returned, and get printed.

Use of lambda function

We use lambda functions mostly when we want a nameless function for a short period. In python, lambda functions are used as an argument for other higher-order functions. Higher-order functions are those functions that take another function as an argument. There are two built-in functions along with which we use lambda functions: map () and filter().

Use with filter( )

Example

# Program to filter out only the odd items from a list
list_val = [1, 5, 4, 6, 8, 11, 3, 12]


list1 = list(filter(lambda x: (x%2 != 0) , list_val))


print(list1)

Output

[1, 5, 11, 3]

Explanation

We used the filter() function in the above code to return the odd numbers from the list. This function takes the lambda function as an argument and the list. After evaluating the expression (x%2 !=0), we will return the value and print the list.

Use of map()

Example

# Program to double each item in a list using map()


list1 = [1, 5, 4, 6, 8, 11, 3, 12]


my_list = list(map(lambda x: x * 2 , list1))


print(my_list)

Output

[2, 10, 8, 12, 16, 22, 6, 24]

Explanation

In the above code, we have the map() function to double all the elements of the list. In the map() function, we have passed the lambda function and the list as an argument, and after that, when the expression( x*2) is evaluated, we return the value.


Related Topics

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

List Assignment Index out of Range in Python

As we know, a List is one of the four unique data structures available in Python; In this tutorial, we will deep dive into understanding iterating through a list and...

3 minutes read.

List Comprehension in Python3

List A list in python is a complex data type, and a list is a collection of the number of data. The data variable may or may not be of the...

5 minutes read.

Iterate through the list in Python

One of the six basic data types of the Python computer language is the list. You must be familiar with the methods and functions that deal with lists in order...

7 minutes read.

How to Read html page in python

Html is a Hyper Text Markup language is a standard language used for creating webpages. HTML is the name of the language used to describe the construction of Web pages....

4 minutes read.

Python oct() function

Python oct() function The oct() function in Python converts an integer number to an octal string prefixed with “0o”. Syntax oct(x) Parameter x: This parameter represents an Integer Number Return This function returns an octal string. Example 1 #...

1 minute read.

Python sklearn train_test_split

Sklearn: One of the most beneficial open-source libraries for learning algorithms in Python is, without a doubt, Sklearn or Scikit-Learn. The most effective tools for statistical modeling and machine learning are all included in...

6 minutes read.

Python Console

Console in Python is referred as the command line Interpreter- (CLI) and also knows as Shell and it functions as taking input from the human user and interpreting it through...

6 minutes read.

FOO in Python

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

Python RegEx

Python RegEx (python regular expressions) is a concept of writing and finding expressions in a pool of characters easily. A Regular expression (RegEx) is a set of characters that defines search...

10 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Python String Variable

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

4 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

OSError in Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

4 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Raise Exception in Python

Most of the programmers/developers create large programs to solve complex tasks in Python. The code can be of 1000 lines and even more based on the need of the problem....

5 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

How to upgrade PIP in python

We use the PIP command in our command prompt to install any package. PIP is used to install published Python packages in the PyPI (Python package index) or other indices....

3 minutes read.

What is the Python Global Interpreter Lock?

Introduction When working with processes, Python employs a form of process lock called the Global Interpreter Lock (GIL). Python typically executes a collection of typed statements using just one thread. It...

4 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.