Python max and min: How to get the max of a list, tuple, set

The max or min calculates the max or min, respectively, of a list, tuple, set, etc.

s = [1, 2, 3]

a = max(s)
b = min(s)

print(a)  # 3
print(b)  # 1

No module is needed to get the max or min. These functions work for Python list, tuple, set.

Max and min of tuple

s = (1, 2, 3)

a = max(s)
b = min(s)

print(a)  # 3
print(b)  # 1

Max and min of set

s = {1, 2, 3}

a = max(s)
b = min(s)

print(a)  # 3
print(b)  # 1

Max and min of dictionary values

d = {
    'Apple': 118,
    'Microsoft': 209,
    'Netflix': 486,
}

a = max(d.values())
b = min(d.values())

print(a)  # 486
print(b)  # 118

To get the max of the dictionary values, use the values() method of dictionary. The values() returns the dictionary values (as a dict_values object) and the max returns the max of them.

Max and min of NumPy array

import numpy

a = numpy.array([[1, 2, 3], [4, 5, 6]])

m1 = numpy.max(a)
m2 = numpy.min(a)

print(m1)  # 6
print(m2)  # 1

NumPy has the similar functions. The max (and of course min) has the axis option.

import numpy

a = numpy.array([[1, 2, 3], [4, 5, 6]])

m = numpy.max(a)
m0 = numpy.max(a, axis=0)
m1 = numpy.max(a, axis=1)

print(m)  # 6
print(m0)  # [4 5 6]
print(m1)  # [3 6]

Max of strings

a = max(['x', 'y'])
b = max(['Microsoft', 'Apple'])

print(a)  # y
print(b)  # Microsoft

The max function can handle a list of strings.

Python Math

Python Tutorial