×

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

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

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

Find Median of List in Python

The median is an enlightening measurement that is utilized as a proportion of the focal inclination of a circulation. It is equivalent to the centre worth of the conveyance. There...

3 minutes read.

Python Stack

Python Stack: The work Stack is defined as arranging a pile of objects or items on top of another. It is the same method of allocating memory in the stack...

10 minutes read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Looping through Data Frame in Python

Iterate over Rows and Columns in Pandas Dataframe This tutorial aims to make us understand what Pandas in Python are, what Data Frame in Python is and its significance, what are...

4 minutes read.

Python String lstrip() method

Python String lstrip() method The string. lstrip () method in Python returns a copy of the string with leading characters removed (based on the string argument passed). Syntax string.lstrip([chars]) Parameter chars(optional): This parameter represents a...

1 minute read.

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to...

5 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

XXhash Python Examples

XXhash Python: xxHash is an extremely rapid hash calculation that operates inside the confines of RAM. Code is incredibly convenient, and hashes (almost nothing/large endian) are same at all levels. Execution of...

4 minutes read.

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

Python Debugger

In this tutorial, we will understand what is debugging in general. Then we will realize what the python debugger means and what is the method to perform it. Now, let us...

3 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.

Python IDE

What is an IDE?  An IDE or an Integrated Development Environment is a type of software where developers can develop many software’s and applications and run the programs inside it. An...

11 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 List sort() method

The list.sort () method in Python sorts the items of the list in place. Syntax list.sort(key=None, reverse=False) Parameter reverse: If a Boolean value ‘True’ is passed, the  sorting will be done in the descending order else for ‘False’...

2 minutes read.

Python program to find factorial of a given number

Python program to find factorial of a given number Factorial is a non-negative integer. It is the product of all positive integers from 1 to the number we are going to...

3 minutes read.

Python String isalpha() method

Python String isalpha() method The string.isalpha () method in Python returns a boolean value true if all characters in the  string are alphabetic else for any other value it returns false. Syntax isalpha()  Parameter NA Return This...

1 minute read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.