Minimum and Maximum of a sequence

suggest change

Getting the minimum of a sequence (iterable) is equivalent of 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 keeps order and max returns the first encountered value. In case 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 containing elements that support \< or \> operations are allowed.

Feedback about page:

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



Table Of Contents