Sitemap

Lambda Function in Python

4 min readApr 24, 2024

--

A lambda function is an anonymous function (i.e. defined without a name) that can take any number of arguments but, unlike normal functions, evaluates and returns only one expression.

They are often used in scenarios where a function is needed temporarily or where defining a full function seems unnecessary. In this article, I will explore lambda functions in detail, including their syntax, use cases, and examples of how they can be used with sorting, mapping, filtering, and reducing data.

Press enter or click to view image in full size

Lambda Function Syntax

lambda arguments: expression

The expression is executed and the result is returned. Here, arguments are the input parameters to the function, and expression is the output that the function will return. Lambda functions can take any number of arguments but can only have one expression.

Example 1:

# Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Output:

15

Example 2:

Lambda functions can take any number of arguments:

multiplication = lambda a,b : a*b
multiplication(2,3)

Output:

6

Example 3:

name = 'Rajesh'
output = lambda a : a.upper()
output(name)

Output:

'RAJESH'

Example 4:

# Multiply argument a with argument b and return the result:

x = lambda a, b : a * b
print(x(5, 6))

Output:

30

Why Use Lambda Functions?

The significance of lambda function is seen when you use them as an anonymous function inside another function.

Get NIRAJAN JHA’s stories in your inbox

Join Medium for free to get updates from this writer.

Say, you have a function definition that takes one argument, and that argument will be multiplied with an unknown number.

def myfunc(n):
return lambda a:a*n
mydoubler = myfunc(2)
mydoubler(11)

Output:

22

Lambda function using conditional expression:

conditional_lambda = lambda x: "Even" if x % 2 == 0 else "Odd"

# Test the lambda function
result = conditional_lambda(4)
print(result)

Output:

Even

Lambda function with if-elif-else logic using nested ternary conditionals:

conditional_lambda = lambda x: "Positive" if x > 0 else ("Zero" if x == 0 else "Negative")

# Test the lambda function
result = conditional_lambda(5)
print(result)

Output:

Positive

1. Mapping in Lambda Functions

Map in Python is a function that works as an iterator to return a result after applying a function to every item of an iterable.

Mapping Syntax

map(function,iterable)

Example 1:

# square the number using lambda function 

num = [2,4,6,8,10]
square_output = list(map(lambda x:x**2,num))
square_output

Output:

[4, 16, 36, 64, 100]

Example 2:

# Find even or odd using lambda function (using conditional statement)

num = [2,29,14,26,98,31,89]
list(map(lambda x:(x,'Even') if x%2 == 0 else (x,'Odd'), num))

Output:

[(2, 'Even'),
(29, 'Odd'),
(14, 'Even'),
(26, 'Even'),
(98, 'Even'),
(31, 'Odd'),
(89, 'Odd')]

Example 3:

# Make a list of words in capital letter

Names = ['Avni','Rahul','Sam','Shravani']
cap_output=list(map(lambda x: x.upper(),Names))
cap_output

Output:

['AVNI', 'RAHUL', 'SAM', 'SHRAVANI']

2. Filtering in Lambda Functions

Filter in Lambda function filters out all the elements of a sequence.

Filtering Syntax

filter(function,iterable)

Example 1:

# Find only even numbers and odd numbers using filters

lis=[1,23,56,7,3,24,66,4,67,54,34]
even = list(filter(lambda x:x%2 == 0,lis))
odd = list(filter(lambda x:x%2 != 0,lis))
print('even =',even)
print('odd =',odd)

Output:

even = [56, 24, 66, 4, 54, 34]
odd = [1, 23, 7, 3, 67]

Example 2:

student_details

[('akash', 70),
('amrutha', 45),
('chandana', 80),
('lokesh', 92),
('mita', 50),
('raju', 90),
('varun', 89)]
# Now print only passed student which is greater than 60 marks 

passed_student = list(filter(lambda x: x[1]>60,student_details))
passed_student

Output:

[('akash', 70), ('chandana', 80), ('lokesh', 92), ('raju', 90), ('varun', 89)]

3. Reduce in Lambda Functions

Reduce in lambda function returns a single output value from a sequence data structure because it reduces the elements by applying a given function. It is used to perform aggregate functions. It is to be noted that always import reduce from functools library if you want to use reduce function.

Reduce Syntax

reduce(function,iterable)

Example 1:

from functools import reduce
nums = [1,2,3,4,5,6,7,8,9,12,19,10]
summed_up = reduce(lambda x,y:x+y,nums)
summed_up

Output:

86

Example 2:

from functools import reduce
# Find the max values from the list

max_values = reduce(lambda x,y: x if x>y else y,nums)
max_values

Output:

19

4. Sorting in Lambda Functions

Sorting can be done in 2 types:

i. sort will directly affect the original list.

ii. sorted sort the list but it does not affect the original list you can save to the different variable.

Example 1:

student_details = [('raju',90),('varun',89),('akash',70),('lokesh',92),('amrutha',45),('chandana',80),('mita',50)]

sorted(student_details,key= lambda x:x[0] ,reverse=True)

Output:

[('varun', 89),
('raju', 90),
('mita', 50),
('lokesh', 92),
('chandana', 80),
('amrutha', 45),
('akash', 70)]

Example 2:

# To sort the marks based on higest to lowest 

Top_students_details = sorted(student_details,key=lambda x:x[1],reverse=True)
Top_students_details

Output:

[('lokesh', 92),
('raju', 90),
('varun', 89),
('chandana', 80),
('akash', 70),
('mita', 50),
('amrutha', 45)]

Example 3:

# Perform using sort function

student_details.sort()


# Now you can see the original list gets affected

student_details

Output:

[('akash', 70),
('amrutha', 45),
('chandana', 80),
('lokesh', 92),
('mita', 50),
('raju', 90),
('varun', 89)]

Conclusion

Lambda functions offer a concise way to create anonymous functions in Python, especially in situations where a full function definition is not needed. They are commonly used in conjunction with functions like sorted(), map(), filter(), and functools.reduce() to perform various operations on data efficiently.

--

--

NIRAJAN JHA
NIRAJAN JHA

Written by NIRAJAN JHA

I write about SQL ,Python and ML for beginners. Learn new contents every day with fun. If you find my articles helpful, feel free to follow.