Search code examples
pythonpython-3.xcomparison

Reason max() returns a different result for an array with same elements


Is there a good explanation why the max() function returns a different result given two arrays below (with the same elements, different ordering)?
Possibly, just the fact it returns the first instance of "max" value which appears after the argument is evaluated?

>>> max([1, False, 0, True])  # returns 1
>>> max([True, False, 0, 1])  # returns True

Solution

  • Value returned by max depends on first value of list:

    print(max([True, 1]))# will return True
    print(max([1, True]))# will return 1
    

    You can use:

    print(bool(max(1, True)))# will return True
    print(bool(max(True, 1)))# also return True
    
    print(int(max(True, 1)))# will return 1
    print(int(max(1, True)))# also return 1
    

    Edit:

    The usage of for example bool(x: int) will convert integer x to boolean value, and int(y: bool) will convert boolean value y to integer.

    With use of this we can ensure what will the max() function return.