Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

max and min in Python

📅 2012-Apr-24 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

With multiple input arguments, max returns the maximum amongst them.

max( 33, 99, 45 )
# 99

With single argument, which must be an iterable, max returns the maximum item in the iterable.

a = ( 33, 99, 45 )
max( a )
# 99
max( "Gandhi" )
# 'n'

max also takes an optional ordering function through its key argument. This function will be called with each item and is expected to return a value that max can use for finding its maximum.

def myfoo( i ):
    if "a" == i: return 10
    if "b" == i: return 99
    if "c" == i: return 50
max( "abc" )
# 'c'
max( "abc", key=myfoo )
# 'b'

All of the above applies to the min function too.

For more information, see Built-in Functions.

Tried with: Python 3.2.2