Integer and Float Maximums in Python’s Max() Function

5/5 - (1 vote)
print(max([3+2, 5*2, 30/3]))
# 10

“Why is the Maximum here 10? Why is float lower than int in identical values? Is there a rule? Thanx!”Albrecht

This excellent question points out the main challenge of this puzzle. Consider the content of the above list [3+2, 5*2, 30/3]:

print([3+2, 5*2, 30/3])
# [5, 10, 10.0]

You can see that the list contains two values that are expected to be mathematically identical 10 and 10.0. So what’s the maximum here?

The answer is both profound and simple. The max function returns the first found maximum as shown in the following example:

print(max([5, 10, 10.0]))
# 10

print(max([5, 10.0, 10]))
# 10.0

It simply returns the highest value in an iterable.

Note that many advanced coders worry that we cannot compare an int with a float because of limited floating point precision because they know the following example:

print(0.3+0.3+0.3 == 0.9)
# False

# 0.8999999999999999

This is not an issue when comparing integers with “integer-like” floats. Python floats can represent integers perfectly fine. Check out the following “proof by example”: 😉

problems = 0

for i in range(10000000):
    if i != float(i):
        problems += 1

# 0

You can see that there’s no integer-float comparison problem.

Leave a Comment