Python : Anonymous/Lambda Functions

Hi all,
Today we are going to discuss about lambda or anonymous function in Python. So let’s explore the lambda.
Lambda in Python
A lambda is a anonymous function which can take any number of arguments but unlike normal functions it can evaluate or return function in only in one expression. It works like def function but can take arguments in only one expression.
Syntax:
lambda arguments : expression
In Python, a lambda function is a special type of function without the function name. For example,
lambda : print('Hello World')
Here, we have created a lambda function which do not gives error
Before exploring more about lambda it’s necessary to know about Python Functions
Using lambda
Add argument num1 and num2 and get the result
# Adding arguments num1 and num2
Addition = lambda num1, num2 : num1 + num2
# Giving values to add
print(Addition(7, 9))
-------------------------------------------------
Output
16
Multiplying num1 argument with num2 argument and get the result
Multiplication = lambda num1, num2 : num1 * num2
print(Multiplication(7, 9))
----------------------------------------------------------
Output
63
Summarize arguments num1, num2, num3, num4 and get the result
# We will give four arguments : num1, num2, num3, num4
Addition = lambda num1, num2, num3, num4 : num1 + num2 + num3 + num4
# We will give four values to add
print(Addition(7, 9, 6, 3))
-------------------------------------------------------------------
Output
25
Uses of lambda function
- Supports single line statements that returns some value.
- Using lambda function can sometime improves the readability of code
- Good for performing short operations/data manipulation
We will use the lambda function with list comprehension
Multiply_numbers = [lambda arg = num1: arg * 9 for num1 in range(1, 11)]
# iterate on each lambda function
for item in Multiply_numbers:
print(item())
-------------------------------------------------------------------
Output
9
18
27
39
45
54
63
72
81
90
We will filter the list of peoples who’s age is more than 18 years using lambda function and filter function
age_people = [7,8,88,75,89,90,5,43,17]
adults = list(filter(lambda age: age > 18, age_people))
print(adults)
------------------------------------------------------------
[88, 75, 89, 90, 43]
Filter all the even numbers from the list
numbers = [75,76,89,87,91,90,767,54]
odd_numbers = list(filter(lambda num:(num%2!=0), numbers))
print(odd_numbers)
-----------------------------------------------------------
Output
[75, 89, 87, 91, 767]
We have very good series of Python articles, please have a look – https://knowledge-junction.in/category/python/
Thank you for reading this article 🙂
Have a nice day!!
How would you rate this article
You must log in to post a comment.