1184

How do I represent minimum and maximum values for integers in Python? In Java, we have Integer.MIN_VALUE and Integer.MAX_VALUE.


See also: What is the maximum float in Python?.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
bdhar
  • 21,619
  • 17
  • 70
  • 86
  • 21
    Note that in Python 3 the `int` type is basically the same as the `long` type in Python 2, so the idea of a maximum or minimum `int` disappears completely. It's basically irrelevant even on Python 2. – agf Sep 30 '11 at 01:42
  • 23
    @agf: it can be relevant in various way. For instance in any algorithm that require to save the min value found (like a sorting algorithm). The min value could be initialized at sys.maxint so it guarantees that any first value found is taken as min – Basile Perrenoud Jan 09 '14 at 15:30
  • 2
    @Toaster except that you can have a list where all values are greater than `sys.maxint` since it's only the maximum for the `int` type on Python 2, which Python will silently promote to a `long`. – agf Jan 09 '14 at 16:17
  • 56
    If you need to use "a very large value" in an algorithm, e.g. finding minimum or maximum of a generic collection, `float('inf')` or `float('-inf')` can be quite helpful. – geoff Oct 25 '15 at 07:49
  • @geoff true, but one caveat for modern code is that floats can't be used as `Literal` in type hints. So you can't say that a list can contain `Union[int, Literal[-inf]]` even though that might be exactly what might be needed for a given application :/ – Christian Jul 13 '20 at 16:57
  • Might worth reading: [\[SO\]: Maximum and minimum value of C types integers from Python (@CristiFati's answer)](https://stackoverflow.com/a/52485502/4788546). – CristiFati Jul 06 '22 at 11:59

11 Answers11

1264

Python 3

In Python 3, this question doesn't apply. The plain int type is unbounded.

However, you might actually be looking for information about the current interpreter's word size, which will be the same as the machine's word size in most cases. That information is still available in Python 3 as sys.maxsize, which is the maximum value representable by a signed word. Equivalently, it's the size of the largest possible list or in-memory sequence.

Generally, the maximum value representable by an unsigned word will be sys.maxsize * 2 + 1, and the number of bits in a word will be math.log2(sys.maxsize * 2 + 2). See this answer for more information.

Python 2

In Python 2, the maximum value for plain int values is available as sys.maxint:

>>> sys.maxint  # on my system, 2**63-1
9223372036854775807

You can calculate the minimum value with -sys.maxint - 1 as shown in the docs.

Python seamlessly switches from plain to long integers once you exceed this value. So most of the time, you won't need to know it.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
senderle
  • 145,869
  • 36
  • 209
  • 233
  • 237
    This number may appear to be arbitrary, but it isn't. 9223372036854775807 is exactly `2^63 - 1`, so you've got a 64-bit int. In general, an n-bit integer has values ranging from `-2^(n-1)` to `2^(n-1) - 1`. – NullUserException Sep 30 '11 at 01:18
  • 29
    Note that if you're using a 32-bit Python runtime, sys.maxint will return `2^31 - 1`, even though Python will jump to 64-bit seamlessly with the `long` datatype. – Scott Stafford Feb 26 '14 at 16:19
  • 29
    Use `sys.maxsize` instead, as suggested by @Akash Rana. It is present also in Python 2, [as `sys` docs](https://docs.python.org/2/library/sys.html#sys.maxsize) say. This will make the code more compatible with both Python versions. – 0 _ Oct 27 '15 at 20:54
  • 1
    @IoannisFilippidis, are you 100% certain the values are the same for all systems and implementations? Until I find something that convinces me that they are, I'm inclined not to make any assumptions. – senderle Nov 01 '15 at 00:42
  • No, there is no guarantee for equality. However, [the docs](http://stackoverflow.com/a/13795777/1959808) say that these are typically equal, and recommends the replacement, which `2to3` [applies](https://docs.python.org/2/library/2to3.html#2to3fixer-renames). – 0 _ Nov 01 '15 at 09:10
  • 11
    You and I have different interpretations of that line from the docs. The replacement in `2to3` is a fine quick-and-dirty heuristic that won't break anything most of the time -- but the difference between these two values matters. The best practice is to use the value you actually mean to use. If you _truly need_ `sys.maxint` in Python 2, you won't need it anymore in Python 3, and it should really be removed entirely, not changed to `sys.maxsize`. – senderle Nov 01 '15 at 12:51
  • 4
    minsize - Multiplying with Bitwise min operator gives minsize ~sys.maxsize – om471987 Oct 14 '16 at 15:33
  • 1
    If there is anybody curious why the maximum positive integer encodable is `2^63 - 1` for 64 bit and `2^31 - 1` for 32 bit checkout this post http://davidalbertoadler.com/twos-complement – david_adler Mar 12 '18 at 19:17
  • 2
    Also [`sys.int_info`](https://docs.python.org/3.4/library/sys.html#sys.int_info) might be of interest. – kyrill Apr 23 '19 at 19:11
  • for the minimum value, why we need `-1` after `-sys.maxsize` ? – Derek Fan Jun 06 '19 at 13:58
  • 2
    @DerekFan because like almost all modern computing platforms, Python uses [two's complement](https://en.wikipedia.org/wiki/Two%27s_complement). Basically, you have an even number of possible values, and zero takes up a slot among the positive values, so there is one more negative value than nonzero positive value. – senderle Jun 06 '19 at 14:32
  • 1
    @DerekFan I should add that it's not just that Python uses two's complement; I'm pretty sure that happens at the level of the processor itself. – senderle Jun 06 '19 at 17:02
  • @MarcoSulla are you saying there's a difference between the maximum array size and the machine's word size? I was not under that impression. I'm inclined to add details if that's the case, rather than simply changing the nomenclature without clarification. – senderle Dec 29 '19 at 22:17
  • @senderle: I linked the official source of the Python docs. Word size are typically 32 or 64 bit, while `Py_ssize_t` is typical `2**31 - 1` or `2**63 - 1`. – Marco Sulla Dec 29 '19 at 22:26
  • @MarcoSulla I think it's splitting hairs to distinguish between the number of bits in a word and the maximum value representable by a word. It's two different ways of measuring the same thing. Also, the docs specifically refer to `sys.maxsize` as the [best place to look for the word sizes](https://docs.python.org/3/library/platform.html#platform.architecture). – senderle Dec 29 '19 at 22:32
  • The docs you linked says that, if you want to know if the Py interpreter is 64 bit, you can do check `sys.maxsize > 2**32`. Indeed, as I wrote and documented, on 32 bit `sys.maxsize` is `2**31-1`. I repeat, `sys.maxsize` is *not* the machine word size, it's the size of the CPython [Py_ssize_t](https://www.python.org/dev/peps/pep-0353/) type, that's a bit different from `size_t` – Marco Sulla Dec 29 '19 at 23:06
  • 1
    OK, yes I see you're talking about the distinction between signed and unsigned. I changed the answer to reflect that distinction. – senderle Dec 29 '19 at 23:19
  • There is still a maximum integer size in python 3. It is just limited by memory allocation bounds rather than cpu instruction bounds. `1 << sys.maxsize` immediately throws an exception. I was curious how to find the allocaiton limit. – fuzzyTew May 27 '22 at 19:13
  • CPython 3 ints [are bounded](https://stackoverflow.com/a/76136809) by the 63-bit integer that stores how many 30-bit unsigned "sub"-integers the int is made out of. In practice they are bounded by how much RAM your computer has. – Boris Verkhovskiy Apr 29 '23 at 14:52
  • sys.min_int would be welcome too... – daruma May 02 '23 at 02:44
487

If you just need a number that's bigger than all others, you can use

float('inf')

in similar fashion, a number smaller than all others:

float('-inf')

This works in both python 2 and 3.

Melle
  • 7,639
  • 1
  • 30
  • 31
  • 16
    Just a note tho (as irrelevant it is, but still): float('inf') > float('inf') results in 'false'. Infinite number should be bigger than another infinite number :-D ... *mind snaps* – Scre Jun 28 '17 at 14:49
  • 39
    @Scre What else would you expect? `x > x` is usually `False`, and infinity should be no exception. (`float('NaN)`, on the other hand...) – jamesdlin Sep 06 '17 at 02:03
  • 14
    This actually doesn't apply for `int` cauze `cannot convert infinite float to int`...but works for most cases – Leighton Sep 23 '17 at 23:16
  • 10
    @Scre "In comparison operations, positive infinity is larger than all values except itself and NaN, and negative infinity is smaller than all values except itself and NaN." http://www.gnu.org/software/libc/manual/html_node/Infinity-and-NaN.html – Nathan Dec 07 '17 at 05:38
  • 15
    This is not an answer to the OP question – Eggcellentos Nov 28 '19 at 12:28
  • 5
    @ghosh maybe not but it answered the question the OP likely had. In Java (and similar) if you want to keep track of a min for example) you can start by storing the max int so that anything else is less than it. In Python you can achieve the same behavior using `float('inf')`, and it works because `float('inf') > a` for any `int` `a`, and since the type of `a` can change freely, you can just set `a = min(a, b)` – cdgraham Dec 23 '21 at 05:06
  • However, in `float('inf') > float('inf')`, could we consider the second float the same number as the first float (itself) and thus is the case of being itself? – Zack Light Jun 09 '22 at 07:46
  • @Scre nope, in maths two (countable at least) infinities are equal, example: series of 1,2,3,..,n is of the same size as 2,4,6,...,2n. Hence float(inf) > float(int) must be False, because float(inf) == float(inf) is proven to be true – Drachenfels Dec 21 '22 at 16:27
  • This doesn't answer OP's question. If he needs to limit his ints to the system max size this won't cut it. – 5px Aug 28 '23 at 19:05
307

The sys.maxint constant has been removed from Python 3.0 onward, instead use sys.maxsize.

Integers

  • PEP 237: Essentially, long renamed to int. That is, there is only one built-in integral type, named int; but it behaves mostly like the old long type.

...

  • The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Akash Rana
  • 3,685
  • 3
  • 19
  • 28
  • 3
    Correct. Indeed, from `help(sys)`: *maxsize -- the largest supported length of containers*. This should be the accepted answer. – Marco Sulla Dec 29 '19 at 21:53
  • I guess that the correct answer depends on the use case: in my casa (a default for a limiting parameter in a function) this was indeed the best answer, YMMV. – Francesco Marchetti-Stasi Mar 13 '22 at 11:12
119

For Python 3, there is no maximum or minimum value for the int type.

You might be interested in sys.maxsize instead. According to the documentation:

sys.maxsize

An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.

import sys
max_size = sys.maxsize
min_size = -sys.maxsize - 1
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
netskink
  • 4,033
  • 2
  • 34
  • 46
  • 60
    well, python 3 does _exist_ , thankfully(!); but `sys.maxint` doesn't exist in python 3 (tl;dr: _"`sys.maxint` constant was removed (in python3), since there is no longer a limit to the value of integers. However, `sys.maxsize` can be used as an integer larger than any practical list or string index."_ ) – michael Jul 16 '17 at 00:33
  • 1
    for the minimum value, why we need `-1` after `-sys.maxsize` ? – Derek Fan Jun 06 '19 at 13:59
  • 3
    Look up 2’s compliment binary – netskink Jun 06 '19 at 14:11
  • 10
    `min = ~sys.maxsize` – Andrew Nov 08 '19 at 04:03
  • What is the bit value of your equation? What happens when you subtract one? Which result is more negative? – netskink Nov 08 '19 at 04:33
  • Here, you go. Count the number of binary digits. `print(bin(sys.maxsize)) 0b111111111111111111111111111111111111111111111111111111111111111 print(bin(-sys.maxsize)) -0b111111111111111111111111111111111111111111111111111111111111111 print(bin(-sys.maxsize-1)) -0b1000000000000000000000000000000000000000000000000000000000000000` – netskink Nov 08 '19 at 14:22
  • 4
    This answer is false. If it were true `sys.maxsize ** 2` would not return a valid and correct value, yet it does. You should delete this answer. – Steven Rumbalski Nov 12 '19 at 17:12
  • 7
    These would work great as sentinel values in algorithms, which is a common usage. Please don’t delete this answer, just make it clear that it’s the most practical one, even if not the most mathematically correct one. – Abhijit Sarkar Mar 07 '21 at 11:41
  • Why would you care to subtract 1 when there is really no minimum value in Python 3? – AlwaysLearning Dec 27 '22 at 10:03
92

In Python 2, integers will automatically switch from a fixed-size int representation into a variable width long representation once you pass the value sys.maxint, which is either 231 - 1 or 263 - 1 depending on your platform. Notice the L that gets appended here:

>>> 9223372036854775807
9223372036854775807
>>> 9223372036854775808
9223372036854775808L

From the Python 2.7 manual:

Numbers are created by numeric literals or as the result of built-in functions and operators. Unadorned integer literals (including binary, hex, and octal numbers) yield plain integers unless the value they denote is too large to be represented as a plain integer, in which case they yield a long integer. Integer literals with an 'L' or 'l' suffix yield long integers ('L' is preferred because 1l looks too much like eleven!).

Python tries very hard to pretend its integers are mathematical integers and are unbounded. It can, for instance, calculate a googol with ease:

>>> 10**100
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000L
Flimm
  • 136,138
  • 45
  • 251
  • 267
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
28

You may use 'inf' like this:

import math
bool_true = 0 < math.inf
bool_false = 0 < -math.inf

Refer: math — Mathematical functions

Georgy
  • 12,464
  • 7
  • 65
  • 73
Rahul Nimbal
  • 525
  • 7
  • 11
  • 6
    Note that `math.inf` is equivalent to `float('inf')` – Georgy Sep 27 '19 at 09:10
  • 3
    The author questioned how to obtain the MAX and MIN int values. How does this answer relates to the question, since the results are True and False, not MAX and MIN? – Gilberto Albino Mar 28 '22 at 11:07
9

If you want the max for array or list indices (equivalent to size_t in C/C++), you can use numpy:

np.iinfo(np.intp).max

This is same as sys.maxsize however advantage is that you don't need import sys just for this.

If you want max for native int on the machine:

np.iinfo(np.intc).max

You can look at other available types in doc.

For floats you can also use sys.float_info.max.

Shital Shah
  • 63,284
  • 17
  • 238
  • 185
6

sys.maxsize is not the actually the maximum integer value which is supported. You can double maxsize and multiply it by itself and it stays a valid and correct value.

However, if you try sys.maxsize ** sys.maxsize, it will hang your machine for a significant amount of time. As many have pointed out, the byte and bit size does not seem to be relevant because it practically doesn't exist. I guess python just happily expands it's integers when it needs more memory space. So in general there is no limit.

Now, if you're talking about packing or storing integers in a safe way where they can later be retrieved with integrity then of course that is relevant. I'm really not sure about packing but I know python's pickle module handles those things well. String representations obviously have no practical limit.

So really, the bottom line is: what is your applications limit? What does it require for numeric data? Use that limit instead of python's fairly nonexistent integer limit.

Run_Script
  • 2,487
  • 2
  • 15
  • 30
Ismael Harun
  • 143
  • 2
  • 7
4

I rely heavily on commands like this.

python -c 'import sys; print(sys.maxsize)'

Max int returned: 9223372036854775807

For more references for 'sys' you should access

https://docs.python.org/3/library/sys.html

https://docs.python.org/3/library/sys.html#sys.maxsize

Amit Dube
  • 321
  • 5
  • 11
Wender
  • 991
  • 15
  • 24
2

On CPython 3.11 on a 64-bit system, the maximum and minimal integers are

  2 ** ((2 ** 63 - 1) * 30) - 1
-(2 ** ( 2 ** 63      * 30) - 1)

You will need 40 exabytes of memory to create one, which would cost $70 billion at today's (July 2023) prices of $57 per 32GB on NewEgg, so in practice Python's maximum integer is limited by how much memory you have in your computer.


CPython 3.11 stores integers like this (I simplified the actual code by taking out all the macros):

struct PyLongObject {
    Py_ssize_t ob_refcnt;  /* Metadata for garbage collection */
    PyTypeObject* ob_type; /* Metadata for type() */
    Py_ssize_t ob_size;    /* Number of items in ob_digit */
    uint32_t ob_digit[1];  /* Array of 32-bit integers */
};

So on a 64-bit system, Python integers are implemented as an array of 32-bit integers storing the absolute value of the integer (but 2 of the bits of each integer aren't used) and a 64-bit signed two's complement integer stores the length of that array as well as the sign of the Python integer, so a negative integer has a negative "size".

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
-3

code given below will help you. for maximum value you can use sys.maxsize and for minimum you can negate same value and use it.

import sys 

ni=sys.maxsize
print(ni)
wjandrea
  • 28,235
  • 9
  • 60
  • 81