Find small number between two numbers using Lambda function in Python

Learn how to find the small number between two numbers using Lambda function in Python?
Submitted by IncludeHelp, on March 13, 2022

Given two numbers (a, b), we have to find the smallest number.

Example:

Input:
a = 10, b = 8

Output: 8

Input: 
a = 20, b = -20

Output: -20

Method 1: Using Lambda Expression and min() Function

Lambda function is an anonymous function - that means the function which does not have any name. And, The min() is an built-in function in Python, which may take N number of arguments and returns the minimum value of its arguments.

Pass the numbers (a and b) to the lambda function and use the min() function to get the small number from a and b.

Python code to find small number using Lambda function and min() function

# Using Lambda function and min() function

small = lambda a, b : min(a,b)

print(small(20, -20))
print(small(10, 8))
print(small(20, 20))

Output:

-20
8
20

Method 2: Using Lambda Expression and Ternary Operator

Pass the numbers (a and b) to the lambda function and compare them using the ternary operator.

Python code to find small number using Lambda function and ternary operator

# Using Lambda function and Ternary Operator

small = lambda a, b : a if a < b else b

print(small(20, -20))
print(small(10, 8))
print(small(20, 20))

Output:

-20
8
20

Python Lambda Function Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.