Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple in Python

Lambda functions in Python

Sometimes, we want to create functions for performing small tasks such as adding two numbers or finding the minimum of two numbers. Now, creating a function is a bit of a task, first of all creating it and then calling it. Lambda functions make it easier to create functions using one line of code. They can take any number of parameters but can return only one value. Let's see how we can use lambda functions.

# function to calculate the sum of two  numbers
def sum(a,b):
    return a + b

print("Using normal function sum of 5 and 6 = " , sum(5,6))

# suml is a lambda function which a and b as parameters and returns a+b
suml = lambda a,b : a + b      

print("Using lambda function sum of 5 and 6 = " , suml(5,6))
    
Output
Using normal function sum of 5 and 6 =  11
Using lambda function sum of 5 and 6 =  11
    
Using Lambda functions, we can concatenate two lists as follows -

l1=[1,2]
l2=[3,4]
a=lambda l1,l2 : l1 + l2

print(a)
print(a(l1,l2))
    
Output
    <function <lambda> at 0x00000211886164D0>
[1, 2, 3, 4]
        
You can also check conditions in a lambda function using if-else statements. The following code checks whether a key is present in a given dictionary or not.

dict1={"rapid": "coders"}
check=lambda dict,key : "Yes" if key in dict.keys() else "No"

print("Key present in dictionary : " , check(dict1,"rapid"))
    
Output
Key present in dictionary : Yes
    

Advantages of Lambda functions

  1. Saves time.
  2. Reduces lines of code.
  3. Easy to understand.
Please note that every function cannot be writen converted to a lambda function but the vice versa is true.