Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Syntax
3.
Difference with normal function
4.
Use cases
4.1.
Lambda function for singular value
4.2.
Lambda function with a list
4.3.
Lambda function for higher-order functions
4.4.
Filter 
4.5.
Map
4.6.
Lambda function using if……else
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024

Lambda Function in Python

Author Malay Gain
1 upvote
gp-icon
Basics of Python
Free guided path
7 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

In Python programming, there is a special kind of anonymous function known as Lambda function which is syntactically different from a regular function. As this function is declared with no name, it is called an anonymous function. Here will be discussing the syntax of the lambda function and its limitation as well as its relevance over regular functions in Python.

Recommended topics, Floor Division in Python, and Convert String to List Python

Syntax

Lambda function is defined without a name. But instead of def keyword, lambda keyword is used to define this function. Let’s see the syntax

lambda arguments: expression

Example

multiply=lambda x,y: x*y

multiply(2,3)

Output

6

Lambda function can have any number of arguments but it is restricted to a single expression. The single expression is evaluated and returned.

Lambda function can be used wherever the function object is required.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Difference with normal function

A regular function can perform multiple operations in its function body but lambda function is synthetically restricted to a single operation. But lambda function is easy to implement for simple logical operations and it can be used to implement such functions that are used just one time.

Both types of functions are implemented for the same objective.

##normal function

def fun(x,y):

  return x*y


fun(2,3)

Output

6

Example

##lambda function

multiply=lambda x,y: x*y

multiply(2,3)

Output

6

 

Must Read Python List Operations

Use cases

Lambda function for singular value

To use the function, just for a single time we don’t need to call the function separately we can pass the values of the arguments along with its definition.

Let’s see through an example

(lambda x,y: x*y)(2,3)

Output

6

In the above lambda function values (2,3) of the arguments (x,y) is passed along with its definition.
 

Lambda function with a list

Lambda function can be used for list comprehension. Let’s implement this scenario using for loop.

list=[lambda x=x: x*10 for x in range (1,6)]

for fun in list:
    print(fun())

Output

10
20
30
40
50


Lambda function for higher-order functions

Lambda function can be used in higher-order functions like filter( ), map( ) that accept a function as its argument. Let’s understand such use cases through the following examples.

Filter 

filter( ) is an inbuilt function in python that only returns the values from a set of values that satisfy a certain condition. Let’s see the syntax of this filter function.

filter(function, iterable)

#we can any anonymous function like lambda function for the 1st argument

#interable can be a list or any set

In the below example we will filter the odd numbers from a list by using lambda function as selection criteria.

lis=[3,4,7,9,2,13,6]

lis=filter(lambda x:x%2==1,lis)

for i in lis:
 print(i)

Output

3
7
9
13

 

Map

The map is also an inbuilt function. Its syntax is the same as filter i.e. filter(function, iterable. It takes any list or tuple and each element is mapped to a different element based on the given function argument. It returns the list of mapped elements.

lis=[1,2,3,4]

mapped=map(lambda x:x*x,lis) #each element mapped to its square



for i in mapped:

  print(i)

Output

1
4
9
16


Lambda function using if……else

We can use a conditional statement to implement the lambda function. Let’s see an example.

min=(lambda x,y:x if x<y else y)
min(2,3)

Output

 2

 

You can practice by yourself with the help of online python compiler.

Also check out Python Square Root here.

FAQs

1. How lambda function is used to manipulate values inside Pandas data frame?
It can be used with apply( ) function to manipulate values of any column. See the below example.

import pandas as pd

df = pd.DataFrame({

    'Name': ['Raj','Tithi','Utkarsh','Kriti'],

    'Birthyear': [2001, 2000, 2002, 1997],

})



df['Age']=df['Birthyear'].apply(lambda x:2022-x) 

## age is calculated using birth year

df

Output


2. Apply lambda function to filter values greater than 10 from a list.

lis=[3,4,7,19,2,13,6]

filtered = list(filter(lambda x:(x>10),lis))



3. Is there any alternative to the lambda function?
Predefined functions in the operator module can be used as an alternative to the lambda function. 

Key Takeaways

This article covered different aspects of lambda function and its use cases.

Recommended Readings:

We recommend you to check out the Coding Ninjas Studio Guided Path on Python programming for learning Python language from basics.

Side by side, you can also practice a wide variety of coding questions commonly asked in interviews in Coding Ninjas Studio. Along with coding questions, you can also find the interview experience of scholars working in renowned product-based companies here. 

Happy learning!

Previous article
Getter and Setter in Python
Next article
Scope of Variable
Guided path
Free
gridgp-icon
Basics of Python
7 chapters
127+ Problems
gp-badge
Earn badges and level up
Live masterclass