5

I am using Python 2.7.x Stack. And using sys.maxint for positive max integer (if it is wrong usage, please feel free to correct me). Sometimes I also need to initialize an integer to be smallest negative integer value. Wondering what is the most elegant/correct way in Python 2.7.x Stack?

Thanks in advance, Lin

Lin Ma
  • 9,739
  • 32
  • 105
  • 175

2 Answers2

15

For comparisons (like to find out smallest value, etc) I normally use float('-inf') , this is not an int, but is smaller than any int, and can be used for commparison with ints. Example -

>>> float('-inf')
-inf

>>> -sys.maxint -1 > float('-inf')
True
Sharon Dwilif K
  • 1,218
  • 9
  • 17
8
-sys.maxint - 1

Negative limits are always one off from positive limits, due to how integers are represented in binary.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • thanks. Why need -1? – Lin Ma Oct 21 '15 at 01:54
  • 1
    Note however that Python does not have a limit for integer values.See http://stackoverflow.com/questions/7604966/maximum-and-minimum-values-for-ints . – jjmontes Oct 21 '15 at 01:54
  • 2
    The `-1` is because in the usual [2's complement](https://en.wikipedia.org/wiki/Two's_complement) representation, zero is positive,so there is space for one extra negative number. Eg signed bytes range from -128 to 127. – jjmontes Oct 21 '15 at 01:59
  • @jjmontes: This is... misleading, depending on how you interpret "integer". At least in Python 2, it does not have a limit for integral values, but it does have a limit for `int` (after `maxint`, they are `long`). – Amadan Oct 21 '15 at 02:02