×

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

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Convert String to Binary in Python

String to binary The strings can be defined as the array of Unicode code characters. Binary Binary is defined as the number system which consists two symbols 0 and 101. It is base-2...

2 minutes read.

Python int()

Python int() class The int() class in Python returns an integer object constructed from a number or string x. Syntax class int(x, base=10) Parameter x: This parameter represents a number or a string that can be converted into...

1 minute read.

Programs for Printing Pyramid Patterns in Python

<!-- wp:paragraph --><p>Python supports printing patterns using basic for loops. The number of rows is handled by the first outer loop, while the number of columns is handled by the...

9 minutes read.

Python ltrim() function

Python ltrim() function The ltrim() function in PHP removes whitespace or other predefined characters from the beginning or left side of a string. The related functions are as follows: rtrim() – This function is used to...

1 minute read.

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 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.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Difference between Python and CPP

Difference between Python and C++ We all know that both C++ and Python are two of the most popular programming languages. Both C++ and Python shares some basic similarities such as...

6 minutes read.

How to append a string in python

Adding or appending a string to another string is easy in Python. It is called concatenation and is a basic concept of strings in almost all programming languages. Ways to Append...

4 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Selection Sort Using Python

Selection sort is a type of sorting algorithm which is based on sorting elements in increasing order or ascending order through comparison. This sorting technique does not take extra space...

3 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.

Import Function in Python

In Python programming language, the import keyword plays an important role in the whole code because it makes one module make available in another module. Import is used to structure...

3 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

How to Convert String to List In Python?

How to Convert String to List In Python? We all are familiar with what strings and lists are, let us have a quick revision on them- Strings are a sequence of characters...

4 minutes read.

Multiprocessing in python

The word multiprocessing is used to compute the operation in which more than two processors run simultaneously with more than one central processor. The computer's performance increases gradually. Multiprocessing is...

6 minutes read.

Python Set difference_update() method

Python Set difference_update() method The set.difference_update() method in Python removes the items that exist in both sets. Syntax set.difference_update(set1) Parameter set- This argument represents a set (minuend) set1- This arguments represents a set(subtrahend) Return None Example 1 # Python program explaining # the set.difference_update()...

2 minutes read.