DEV Community

Cover image for Python: did you know (tip 1)
Muhammad Faizan Khurshid
Muhammad Faizan Khurshid

Posted on

Python: did you know (tip 1)

Did yoy know
By default, "max" function returns the largest of its provided arguments. But if we provide an optional "key" argument, it returns the argument x that maximizes key(x) (aka the 'argmax').

For example if the requirement is to find the a number which gives the largest remainder when divided by 5 or which has larger x % 5, we do it using the "max" function.

def mod_5(x):
"""Return the remainder of x after dividing by 5"""
return x % 5

max(100, 51, 14, key=mod_5)

Output:
14

Top comments (0)