Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python - Lambda function to find the smaller value between two elements
Lambda functions are anonymous functions in Python that provide a concise way to write small operations without defining a full function. In this article, we'll explore different methods to find the smaller value between two elements using lambda functions.
Using Conditional Expression (if-else)
The most straightforward approach uses Python's conditional expression within a lambda function ?
# Direct lambda with conditional expression
smaller = lambda a, b: a if a < b else b
a = 45
b = 24
result = smaller(a, b)
print(f"The smaller number between {a} and {b} is: {result}")
The smaller number between 45 and 24 is: 24
Using min() Function
The min() function returns the smallest value among arguments. We can wrap it in a lambda for consistency ?
Syntax
min(arg1, arg2, ..., argN, key=func)
Example
# Lambda function using min()
find_smaller = lambda a, b: min(a, b)
a = 47
b = 24
result = find_smaller(a, b)
print(f"The smaller number between {a} and {b} is: {result}")
The smaller number between 47 and 24 is: 24
Using sorted() Method
The sorted() function returns a new sorted list. We can take the first element to get the smallest value ?
Syntax
sorted(iterable, key=key, reverse=Boolean)
Example
# Lambda function using sorted()
find_smaller = lambda a, b: sorted([a, b])[0]
a = 455
b = 89
result = find_smaller(a, b)
print(f"The smaller number between {a} and {b} is: {result}")
The smaller number between 455 and 89 is: 89
Using reduce() Function
The reduce() function from the functools module applies a function cumulatively to items in an iterable ?
from functools import reduce
# Lambda function with reduce
smaller = lambda a, b: a if a < b else b
numbers = [4557, 66]
result = reduce(smaller, numbers)
print(f"The smaller number between {numbers[0]} and {numbers[1]} is: {result}")
The smaller number between 4557 and 66 is: 66
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Conditional Expression | High | Fastest | Simple two-value comparison |
min() |
Highest | Fast | Built-in clarity |
sorted() |
Medium | Slower | When you need sorted order |
reduce() |
Low | Medium | Multiple values or functional style |
Conclusion
For finding the smaller value between two elements, use min() for clarity or conditional expression for performance. Lambda functions provide elegant one-liner solutions for simple comparison operations.
