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 print(0.3+0.3+0.3) # 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 print(problems) # 0
You can see that there’s no integer-float comparison problem.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.