Introduction to Python
Programming Cycle of Python
Varibles and Datatypes in Python
Input and Output in Python
Operators in Python
Precedence of Operators in Python
Typecasting in Python
If Else in Python
Loops in Python
Break, Continue and Pass in Python
Functions in Python
Default Arguments and Keyword Arguments in Python
Strings in python
Lists in Python
Tuple in Python
Dictionary in Python
Sets in Python
List Comprehension in Python
Unpacking Sequences in Python
Higher Order Functions in Python
Lambda Functions in Python
Sieve of Eratosthenes Algorithm in Python
Linear Search in Python
Binary Search in Python
Selection Sort in Python
Bubble Sort in Python
Insertion Sort in Python
Merge Sort 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
- Saves time.
- Reduces lines of code.
- Easy to understand.
Please note that every function cannot be writen converted to a lambda function but the vice versa is true.