For numerical comparisons, +- float("inf") should work.

It doesn't always work (but covers the realistic cases):

print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so not a real issue.

To have objects that compare as higher or lower to any other arbitrary objects (including inf, but excluding other cheaters like below), you can create classes that state their max/min-ness in their special methods for comparisons:

class _max:
    def __lt__(self, other): return False
    def __gt__(self, other): return True

class _min:
    def __lt__(self, other): return True
    def __gt__(self, other): return False

MAX, MIN = _max(), _min()

print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")])))
# [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>]

Of course, it takes more effort to cover the 'or equal' variants. And it will not solve the general problem of being unable to sort a list containing Nones and ints, but that too should be possible with a little wrapping and/or decorate-sort-undecorate magic (e.g. sorting a list of tuples of (typename, value)).

Answer from TryPyPy on Stack Overflow
🌐
Note.nkmk.me
note.nkmk.me › home › python
Maximum and Minimum float Values in Python | note.nkmk.me
August 11, 2023 - A normalized number is a value whose exponent part is not 0. sys.float_info.min is as follows in hexadecimal.
Top answer
1 of 3
16

For numerical comparisons, +- float("inf") should work.

It doesn't always work (but covers the realistic cases):

print(list(sorted([float("nan"), float("inf"), float("-inf"), float("nan"), float("nan")])))
# NaNs sort above and below +-Inf
# However, sorting a container with NaNs makes little sense, so not a real issue.

To have objects that compare as higher or lower to any other arbitrary objects (including inf, but excluding other cheaters like below), you can create classes that state their max/min-ness in their special methods for comparisons:

class _max:
    def __lt__(self, other): return False
    def __gt__(self, other): return True

class _min:
    def __lt__(self, other): return True
    def __gt__(self, other): return False

MAX, MIN = _max(), _min()

print(list(sorted([float("nan"), MAX, float('inf'), MIN, float('-inf'), 0,float("nan")])))
# [<__main__._min object at 0xb756298c>, nan, -inf, 0, inf, nan, <__main__._max object at 0xb756296c>]

Of course, it takes more effort to cover the 'or equal' variants. And it will not solve the general problem of being unable to sort a list containing Nones and ints, but that too should be possible with a little wrapping and/or decorate-sort-undecorate magic (e.g. sorting a list of tuples of (typename, value)).

2 of 3
11

You have the most obvious choices in your question already: float('-inf') and float('inf').

Also, note that None being less than everything and the empty tuple being higher than everything wasn't ever guaranteed in Py2, and, eg, Jython and PyPy are perfectly entitled to use a different ordering if they feel like it. All that is guaranteed is consistency within one running copy of the interpreter - the actual order is arbitrary.

🌐
GeeksforGeeks
geeksforgeeks.org › python-min-max-value-in-float-string-list
Python | Min/Max value in float string list - GeeksforGeeks
April 8, 2023 - Method 1: Using min()/max() + float() This problem can be solved using the min or max function in which we first convert the strings into float and then pass this logic in functions in respective min/max function.
🌐
W3Resource
w3resource.com › python-interview › what-is-the-maximum-and-minimum-value-for-an-int-float-and-string-data-type-in-python.php
Exploring data type limits in Python
August 12, 2023 - Maximum and minimum values for integer and float data types: Max Int: 9223372036854775807 Min Int: -9223372036854775808 Max Float: 1.7976931348623157e+308 Min Float: 2.2250738585072014e-308 Note: The values provided by sys.maxsize and sys.float_info ...
🌐
Python Forum
python-forum.io › thread-25187.html
Python sys.float_info.min value
There is sys.float_info in Python: >>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-3
🌐
DEV Community
dev.to › frankkk › python-tips-floatinf-269h
Python Tips- Maximum Value float('inf') - DEV Community
February 3, 2024 - Here is a question: what is the maximum value in Python? For the float, we can use sys.float_info to check the details. >>> import sys >>> sys.float_info sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1) >>> print(sys.float_info.max) 1.7976931348623157e+308 ·
🌐
TutorialsPoint
tutorialspoint.com › What-is-the-maximum-value-of-float-in-Python
What is the maximum value of float in Python?
Maximum float value: 1.7976931348623157e+308 Minimum positive normalized float: 2.2250738585072014e-308 Float epsilon: 2.220446049250313e-16
Find elsewhere
🌐
Statistics Globe
statisticsglobe.com › home › python programming language for statistics & data science › print lowest & highest float in list in python (3 examples)
Print Lowest & Highest Float in Python List | Smallest / Largest Item
May 4, 2023 - In this Python article, you’ll learn how to print the lowest and highest float in a list. The content in this article is structured as follows: ... 2) Example 1: Use max() & min() Functions Along With List Comprehension to Print Maximum & Minimum Float in List
🌐
TutorialsPoint
tutorialspoint.com › article › get-the-machine-limits-information-for-float-types-in-python
Get the Machine limits information for float types in Python
February 24, 2022 - Float64 machine limits: Minimum value: -1.7976931348623157e+308 Maximum value: 1.7976931348623157e+308 Machine epsilon: 2.220446049250313e-16 Precision: 15 Smallest positive number: 2.2250738585072014e-308 · Use numpy.finfo() to get machine ...
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.finfo.html
numpy.finfo — NumPy v2.5 Manual
The number of bits in the exponent portion of the floating point representation. ... The exponent that yields eps. ... The largest representable number. ... The smallest positive power of the base (2) that causes overflow. Corresponds to the C standard MAX_EXP.
🌐
Stack Overflow
stackoverflow.com › questions › 71439176 › how-to-use-min-function-for-floats
python - How to use min() Function for floats - Stack Overflow
I am trying to find out the minimum value within a user define function.The values that are within the loop are float.But somehow I was unable to use min function for my conditional statement.My code is given below: Copydef life_age(x): for i in range(1,16): if 0<min(x[f'age_{i}'])<18: return 1 ... @paul You should because the if-statement doesn't have a body. This is not legal Python.
Top answer
1 of 3
14

Frst, if you care about performance in Python (which isn't always a sensible thing to care about, but that's another conversation), you should be using the timeit module. Even in C it's hard to predict how certain functions will behave after compilation, and it's harder in Python. People are often confidently expressing opinions about which functions are faster which are data-dependent. Then -- by using timeit, I mean -- you could've found out yourself.

Second, if you really care about performance on lists of floats, you shouldn't be using lists at all, but numpy arrays. Using IPython here, under Python 2.7.2, which makes timing things easy:

In [41]: import random, numpy
In [42]: a = [0.1*i for i in range(10**5)]
In [43]: timeit min(a)
100 loops, best of 3: 4.55 ms per loop
In [44]: timeit sorted(a)[0]
100 loops, best of 3: 4.57 ms per loop
In [45]: random.shuffle(a)
In [46]: timeit min(a)
100 loops, best of 3: 6.06 ms per loop
In [47]: timeit min(a) # to make sure it wasn't a fluke
100 loops, best of 3: 6.07 ms per loop
In [48]: timeit sorted(a)[0]
10 loops, best of 3: 65.9 ms per loop
In [49]: b = numpy.array(a)
In [50]: timeit b.min()
10000 loops, best of 3: 97.5 us per loop

And we note a few things. (1) Python's sort (timsort) works very well on data which has sorted runs, so sorting an already sorted list has almost no penalty. (2) Sorting a random list, on the other hand, is very much slower, and this will only get worse as the data gets larger. (3) Numpy.min() on a float array works sixty times faster than min on a Python list, because it doesn't have to be as general.

2 of 3
12

If the list is already populated, min() is the most efficient way.

There are some tricks you might use in special scenarios:

  • If you build the list from scratch, simply keep the smallest item yet in an external variable, so that the answer will be given in O(1).
  • If there are only Floats in the list, use an Array which gives better performance.
  • You can keep the list sorted using bisect.
  • Use a Python Heap, which even has an efficient implementation of min(). Make sure you understand the effects, mainly a slower insertion. (credit: interjay)
🌐
Python.org
discuss.python.org › python help
Smallest positive number machine can store - Python Help - Discussions on Python.org
June 3, 2021 - If we run the following code s=1 while s>0 : print(s) s=s/10 the last output is 10^-323 If we run the following one s=1 a=1+s while a> 1: print(s) s=s/10 a=1+s the last output is 10^-15 The two results appear to be inconsistent.
🌐
Stack Abuse
stackabuse.com › bytes › maximum-and-minimum-values-for-integers-in-python
Maximum and Minimum Values for Integers in Python
September 11, 2023 - You can find the maximum and minimum float values using the sys.float_info object, which is part of Python's sys module.
🌐
Sololearn
sololearn.com › en › Discuss › 1265007 › how-does-max-and-min-function-workequal-float-numbers-in-python
How does max and min function work(equal float numbers) ...
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › find maximum float value in python
Find Maximum Float Value in Python - Spark By {Examples}
May 31, 2024 - How to find the maximum float value in Python? You can find the maximum value of the float data type using the sys.float_info module or the finfo()
🌐
Programiz
programiz.com › python-programming › methods › built-in › min
Python min()
The Python min() method returns the smallest item in an iterable. It can also be used to find the smallest item between two or more parameters.