ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.