Minimum and Maximum of a sequence

suggest change

Getting the minimum of a sequence (iterable) is equivalent to accessing the first element of a sorted sequence:

min([2, 7, 5])
# Output: 2
sorted([2, 7, 5])[0]
# Output: 2

The maximum is a bit more complicated, because sorted is stable and max returns the first maximum it encounters. When there are no duplicates, the maximum is the same as the last element of the sorted return:

max([2, 7, 5])
# Output: 7
sorted([2, 7, 5])[-1]
# Output: 7

But not if there are multiple elements that are evaluated as having the maximum value:

class MyClass(object):
    def __init__(self, value, name):
        self.value = value
        self.name = name
        
    def __lt__(self, other):
        return self.value < other.value
    
    def __repr__(self):
        return str(self.name)

sorted([MyClass(4, 'first'), MyClass(1, 'second'), MyClass(4, 'third')])
# Output: [second, first, third]
max([MyClass(4, 'first'), MyClass(1, 'second'), MyClass(4, 'third')])
# Output: first

Any iterable whose elements support < or > is allowed.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents