max() in python code example

Example 1: python maths max value capped at x

def clamp(n, minn, maxn):
    return max(min(maxn, n), minn)

Example 2: python largest value in list

>>> list = [1, 3, 2, 0]
>>> max(list)
3

Example 3: max value in python

# find largest item in the string
print(max("abcDEF")) 

# find largest item in the list
print(max([2, 1, 4, 3])) 

# find largest item in the tuple
print(max(("one", "two", "three"))) 
'two'

# find largest item in the dict
print(max({1: "one", 2: "two", 3: "three"})) 
3

# empty iterable causes ValueError
# print(max([])) 

# supressing the error with default value
print(max([], default=0))

Example 4: python max function

square = {2: 4, -3: 9, -1: 1, -2: 4}

# the largest key
key1 = max(square)
print("The largest key:", key1)    # 2

# the key whose value is the largest
key2 = max(square, key = lambda k: square[k])

print("The key with the largest value:", key2)    # -3

# getting the largest value
print("The largest value:", square[key2])    # 9

Example 5: how to get maximum value of number in python

float('inf')

Example 6: python max()

i = max(2, 4, 6, 3)

print(i)
# Result will be 6 because it is the highest number

Tags:

Java Example