×

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 And Operator

Python's and operator takes two operands that can be either object, Boolean expressions, or both. And operator creates more complex expressions using those operands. Conditions are the common name for...

8 minutes read.

Convert string into int in Python

String A string is defined as a series of characters, special characters, and numbers. A string is traditionally a sequence of characters, either as a literal constant or as some kind of variable. The latter may allow its elements...

2 minutes read.

Python Dictionary update() method

Python Dictionary update() method The dictionary.update() method in Python inserts the specified items to the dictionary. Syntax dictionary.update(iterable) Parameter iterable- This parameter represents a dictionary or an iterable object with key value pairs, that will...

1 minute read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Difference between Expression and Statement in Python

What is an expression in Python? Expression is a combination of operands and operators. Expression helps us to produce some other values. In the python programming language,  expressions produce some other value...

6 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

Static Variables in Python

What is a Static Variable? The variable that remains with a constant value throughout the program or throughout the class is known as a " Static Variable ". Static variables are...

3 minutes read.

Speech Recognition Module in Python

Speech Module in Python: Converting text to speech, known as Speech Synthesis, this process is the computer-generated recreation of human speech. This module converts the human language text into human-like...

8 minutes read.

Python Comment Block

In this tutorial, we will see what comment blocks mean in Python. Further, we will see the commenting methods supported in Python. We will understand the topics deeply with the...

6 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Index Error in Python

The index errors are the run time error that is raised in Python when we try to access an index that does not exist. This might seem very trivial but...

4 minutes read.

How to Pass a list as an Argument in Python

Lists in Python A list is a datatype in python which is used to store the data in a sequence. The lists are mutable; that is, we can change the values...

3 minutes read.

Python Boolean

In this article, you will learn the boolean variables in python, bool() function in python, and bool operators with examples, Boolean Objects in Python. There are the only two possible values...

6 minutes read.

Python 2.7 data structures

The rundown information type has a few additional techniques. Here is every one of the strategies for listing objects: list.append(x): Add a thing to the furthest limit of the rundown; comparable...

9 minutes read.

Django vs NodeJS

Django and NodeJS are open-source frameworks used to develop web applications. Both Django and NodeJS are cross-platform and robust technology used for developing versatile web applications and mobile applications. Django Django is...

2 minutes read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

How to change the names of Columns in Python

Introduction To play with huge amounts of data, in Python we require a tool. The tool which is available in Python is Pandas. Pandas is an open-source library. It is used...

3 minutes read.

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

How to convert Float to Int in Python?

A float value can be converted to an int via type conversion, an explicit method of transforming an operand to a certain type. But it must be noted that such...

3 minutes read.