How to Code a Shorter Max Function in Python?

Estimated read time 1 min read

The built-in max() function in Python is already quite concise and efficient. However, if you’re looking for an alternative implementation, you can use the reduce() function from the functools module to achieve a shorter version:

from functools import reduce

def max_value(a, b):
    return a if a > b else b

numbers = [3, 7, 2, 9, 1, 5]
maximum = reduce(max_value, numbers)

print("Maximum value:", maximum)

In this example, the max_value() function compares two values and returns the greater one. By using reduce() with max_value() as the reducing function, we can find the maximum value in the numbers list.

Please note that while this code provides an alternative implementation, the built-in max() function is generally recommended for its simplicity and optimized performance.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply