alternative
  • Home (current)
  • About
  • Tutorial
    Technologies
    C#
    Deep Learning
    Statistics for AIML
    Natural Language Processing
    Machine Learning
    SQL -Structured Query Language
    Python
    Ethical Hacking
    Placement Preparation
    Quantitative Aptitude
    View All Tutorial
  • Quiz
    C#
    SQL -Structured Query Language
    Quantitative Aptitude
    Java
    View All Quiz Course
  • Q & A
    C#
    Quantitative Aptitude
    Java
    View All Q & A course
  • Programs
  • Articles
    Identity And Access Management
    Artificial Intelligence & Machine Learning Project
    How to publish your local website on github pages with a custom domain name?
    How to download and install Xampp on Window Operating System ?
    How To Download And Install MySql Workbench
    How to install Pycharm ?
    How to install Python ?
    How to download and install Visual Studio IDE taking an example of C# (C Sharp)
    View All Post
  • Tools
    Program Compiler
    Sql Compiler
    Replace Multiple Text
    Meta Data From Multiple Url
  • Contact
  • User
    Login
    Register

Python - Lambda Function - Lambda Function Tutorial

Python Lambda Functions are anonymous function means that the function is without a name.

Syntax-

lambda arguments: expression
  • This function can have any number of arguments but only one expression, which is evaluated and returned.
  • Lambda function is a short syntax or one-line code

 

Example-

# creating lambda function to sum a and b, and assigning it to c
x = lambda a,b: a + b

# calling lambda function using variable x
x(10,20)

Output-

30

In the above example, we defined a lambda function(x) that sum up a two value a and b

 

Use Of lambda function in python-

Condition checking using python lambda function

Example-

# creating lambda function to check whether the number is even or odd
a = lambda a:"even" if a%2==0 else 'odd'

# calling lambda function using variable a
a(10)

Output-

even

 

Condition checking using python def function

Example-

def evenorodd(x):
    if(x%2==0):
        return "even"
    else:
        return "odd"

print(evenorodd(10))

Output-

even

 

Def Function vs Lambda Function

Def Function

Lambda Function

More than one line of code

One line of code that return some value

Good for performing where multiple operation or condition check need to be performed

Good for performing short operation like arithmetic operation or condition check

Comments can be used to for easy readabilty

It reduce the readability of code

 

List Comprehension vs Lambda Function

We can achieve short syntax or one line of code from List Comprehension also. List Comprehension is a built-in function and can create and modify the list in fewer lines of code.

But the problem with the lambda function is, that it will return something, otherwise, it will give an error, if the value is not returned.

Example-

email=['12345@gmail.com','vaibsm@outlook.com','sam@hotmail.com','helpdesk@fresherbell.com']

# Using list comprehension it will take 1 line to extract only alphabetic username
username2=[i.split('@')[0] for i in email if i.split('@')[0].isalpha()]
print(username2)

# Also using lambda function it will take 1 line to extract only alphabetic username
username3=list(map(lambda x: x.split('@')[0] if(x.split('@')[0].isalpha()) else "", email))
print(username3)

#It will give error, if value is not returned
username4=list(map(lambda x: x.split('@')[0] if(x.split('@')[0].isalpha()), email))
print(username4)

Output-

['vaibsm', 'sam', 'helpdesk']
['', 'vaibsm', 'sam', 'helpdesk']

 File "C:\Users\ssaur\AppData\Local\Temp/ipykernel_9892/2835995980.py", line 8
    username4=list(map(lambda x: x.split('@')[0] if(x.split('@')[0].isalpha()), email))
                                                                              ^
SyntaxError: invalid syntax

 

In the above example,

in a part of username3, it returns some value if the value is true, otherwise, it will return an empty string on false

in a part of username4, it returns some value if the value is true, but there is no else condition. hence nothing is returned in else part. which will throw an error.

Hence, list comprehension is a more readable and elegant way to define logic than the lambda function.

 

Using lambda() Function with filter()

The filter() function accepts two arguments in Python: a function and a list. It filters out all the elements from the list for which the function returns true.

Example-

email=['12345@gmail.com','vaibsm@outlook.com','sam@hotmail.com','helpdesk1@fresherbell.com']

# Using filter with lambda it will extract email whose username is alphabetic
username3=list(filter(lambda x: x.split('@')[0].isalpha(), email))
print(username3)

Output-

['vaibsm@outlook.com', 'sam@hotmail.com']

 

Using filter() without lambda

Function needs to return bool value. this function will be applied to every element of the iterable.

Program to find even numbers from the list.

Example-

number=[102, 10, 99, 32, 113]

def even_check(n):
    if n%2==0:
        return True

# Using map with lambda function it will return new list in celcius
even=list(filter(even_check, number))
print(even)

Output-

[102, 10, 32]

 


 

Using lambda() Function with map()

The map() function accepts two arguments in Python: a function and a list. It return new list which contains all the lambda modified items returned by that function for each item.

Program  to find username from email using lambda and map function

Example-

email=['12345@gmail.com','vaibsm@outlook.com','sam@hotmail.com','helpdesk1@fresherbell.com']

# Using map with lambda function it will return new list of username extracted from email list
username3=list(map(lambda x: x.split('@')[0], email))
print(username3)

Output-

['12345', 'vaibsm', 'sam', 'helpdesk1']

 

Using map() without lambda

Program to find Celcius from Fahrenheit number

Example-

faherenheit=[102, 101, 99, 120, 113]

def cel(T):
    return (5/9)*(T-32)

# Using map with lambda function it will return new list in celcius
celcius=list(map(cel, faherenheit))
print(celcius)

Output-

[38.88888888888889, 38.333333333333336, 37.22222222222222, 48.88888888888889, 45.0]

 

Using lambda() Function with reduce()

The reduce() function accepts two arguments in Python: a function and a list. It performs a repetitive operation over the pairs of the iterable and return a new reduced result. The reduce() function belongs to the functools module.

Here, 1st element is added to 2nd element.result of both will get added to 3rd element, and this goes on till the end of the list like (((('Hello ', + 'welcome ') + 'to ') + 'fresherbell ') + 'website ')

Example-

from functools import reduce
li = ["Hello ", "Welcome ", "to ", "fresherbell ", "website"]
str1 = reduce((lambda x, y: x + y), li)
print(str1)
Output-
Hello Welcome to fresherbell website

 
Python

Python

  • Introduction
  • Installation and running a first python program
    • How to install Python ?
    • Running 1st Hello World Python Program
    • How to install Pycharm ?
  • Things to know before proceed
    • Escape Characters/Special Characters
    • Syntax ( Indentation, Comments )
    • Variable
    • Datatype
    • Keyword
    • Literals
    • Operator
    • Precedence & Associativity Of Operator
    • Identifiers
    • Ascii, Binary, Octal, Hexadecimal
    • TypeCasting
    • Input, Output Function and Formatting
  • Decision control and looping statement
    • if-else
    • for loop
    • While loop
    • Break Statement
    • Continue Statement
    • Pass Statement
  • Datatype
    • Number
    • List
    • Tuple
    • Dictionary
    • String
    • Set
    • None & Boolean
  • String Method
    • capitalize()
    • upper()
    • lower()
    • swapcase()
    • casefold()
    • count()
    • center()
    • endswith()
    • split()
    • rsplit()
    • title()
    • strip()
    • lstrip()
    • rstrip()
    • find()
    • index()
    • format()
    • encode()
    • expandtabs()
    • format_map()
    • join()
    • ljust()
    • rjust()
    • maketrans()
    • partition()
    • rpartition()
    • translate()
    • splitlines()
    • zfill()
    • isalpha()
    • isalnum()
    • isdecimal()
    • isdigit()
    • isidentifier()
    • islower()
    • isupper()
    • isnumeric()
    • isprintable()
    • isspace()
    • istitle()
  • Python Function
    • Introduction
  • Lambda Function
    • Lambda Function
  • Python Advanced
    • Iterators
    • Module
    • File Handling
    • Exceptional Handling
    • RegEx - Regular Expression
    • Numpy
    • Pandas

About Fresherbell

Best learning portal that provides you great learning experience of various technologies with modern compilation tools and technique

Important Links

Don't hesitate to give us a call or send us a contact form message

Terms & Conditions
Privacy Policy
Contact Us

Social Media

© Untitled. All rights reserved. Demo Images: Unsplash. Design: HTML5 UP.