How Lambda Expression Works in Python?

  • By Pooja Nandode-Bhavsar
  • January 16, 2025
  • Python
How Lambda Expression Works in Python?

How Lambda Expression Works in Python?

In Python, lambda expressions are the kind of functions that need not to give any name and hence, the lambda function is also called an “anonymous(nameless) function”. A lambda expression is a way to create small, anonymous functions using a simple syntax. It is often used for functions that are simple, short, and typically passed as arguments to higher-order functions. Learn how Lambda Expression works in Python? with this concise guide. Understand syntax, use cases, and examples to simplify coding with anonymous functions.

 

Key features of Lambda Expression:

  •  Lambda functions are written in a single line, which makes them more compact compared to regular functions.
  • A lambda function doesn’t need a name. It’s useful when a function is needed temporarily or for short operations.
  •  Lambda functions are limited to a single expression. They cannot contain statements or multiple expressions.

 

Syntax of a Lambda Expression:

lambda arguments: expression

arguments: These are the input parameters for the lambda function. You can have multiple parameters or none at all.

expression: This is a single expression whose result is returned by the lambda function. The expression can contain operations or logic, but it must return a value.

In lambdas, the part before :(colon) is called a function declaration,and part after the colon is called a function definition/body

 

Creating lambda expression in several ways,

 

1. without lambda function

def add(x,y):

   z=x+y

   print(“without lambda,add  =”,z)

 

add(5,3)

 

2. with lambda function/expression/anonymous function

lambda expression with parameter but without return statement

add1=lambda x,y: print(“With lambda,add  =”,x+y)

add1(5,6)

 

here, in above code “lambda x,y:” is the function declaration

“print(“With lambda,add  =”,x+y)” function definition

and add1(5,6)” function calling

 

3.lambda expression withOUT parameter and without return statement

add2=lambda : print(“lambda without parameter”)

add2()

 

4.lambda expression with parameter and with return statement(don’t need to specify/use return keyword in lambda expression)

add3=lambda x,y:x+y   #return

print(“lambda with return statement ,add3  = “,add3(5,6))

 

IIFE(Immediately Invoked(calling) Function Execution)=> means the function is callable as soon as it is defined

lambda function with parameters like x,y,z

print( (lambda x,y,z:x+y+z) (5,6,8))

 

lambda function withOUT parameters

def msg():

   print(“hello everyone!! Without Lambda….”)

 

msg()

 

Using IIFE

print( (lambda  :  print(“hello everyone!! With Lambda ….”)) () )

 

lambda expression is executed only when we call it or we print it

 

  • lambdas can return string

x=lambda : “hello user”

print(x())

 

  • lambdas can return number

square=lambda : 7*7

print(“square of 7 :”,square())

 

  • lambdas can return boolean value

z=lambda : True

print(z())

 

  • lambdas with if else statement

evenOdd=lambda n : “even no” if (n % 2==0)  else “odd no”

print(evenOdd(39))

 

positiveNo=lambda k : “positive no” if (k> 0)  else “negative no”

print(positiveNo(-39))

 

  • lambdas with elif  statement

#student marks grade system

 

grade = lambda marks :   “fail” if (marks < 50)\

                         else “D grade” if (marks >= 50 and marks < 70) \

                         else “B grade” if (marks >= 70 and marks < 90) \

                         else “A grade” if (marks >= 90 and marks <= 100)\

                         else “Invalid marks”

print(grade(700))

 

#finding vowles or consonent

findingVowelsOrConsonent= lambda  char : “vowel” if  char==’a’ or  char==’e’  or char==’i’ or char==’o’ or char==’u’ or char==’A’ or  char==’E’  or char==”I” or char==’O’ or char==’U’  else “consonent”

 

findingVowelsOrConsonent(‘i’)

 

#iterating with lambdas using for in loop

 

#without lambda

l1=[4,7,1,3,7,9,8]

l2=[]

print(“*********without lambda**********”)

print(“l1 = “,l1)

  #4

for n in l1:

   #n**3      #4*4*4 => cube

   sq=n ** 2  # 4*4   => squre

   l2.append(sq)

 

print(“square of nums present in l2 =”,l2)

 

#————————————————————-

#with lambda

l3=[7,5,9,2,11,4,21]

l4=[]

 

print(“*********with lambda**********”)

print(“l3 = “,l3)

 

for n in l3:

   sq=lambda n : n ** 2  #here, sq is function like sq()

   l4.append(sq(n))    

print(“square of nums present in l3 =”,l4)

 

For Free, Demo classes Call: 02071171500

Registration Link: Click Here!

 

Advantages of Lambda Expressions:

  • Short and Readable: Lambda functions are ideal for small operations, reducing the need for full function definitions.
  • Functional Programming: They are a key feature of functional programming, allowing functions to be passed around easily as arguments.

 

Limitations:

  • Single Expression: Lambda functions can only contain a single expression, which limits their use in more complex scenarios.
  • Readability: Although compact, lambda functions can sometimes be less readable, especially for more complex operations.

In conclusion, lambda expressions in Python provide a succinct way to define small functions, and they are especially useful in cases where a function is needed temporarily or for simple tasks.

 

Note: Do watch our latest video: Click Here

Author:-

Pooja Nandode-Bhavsar

Call the Trainer and Book your free demo class Python for now!!!

© Copyright 2020 | SevenMentor Pvt Ltd.