To find the maximum and minimum values for an integer we use maxsize method from the sys module. The sys.maxsize gives us the maximum value whereas the negative version of this value i.e. -sys.maxsize-1 gives us the minimum value for the integer. Also, we can get the max and min values of integers using numpy module in Python
In this post, we will cover the details of how we get the maximum and minimum values for the integers using the two methods that are:
- Method 1: Using maxsize method from the sys module.
- Method 2: Using the Numpy module in Python.
How to Find Maximum/Minimum Values for Integers in Python?
There are two major ways to find the minimum and maximum values for integers in Python. let’s discuss them one by one.
Method 1: Using maxsize method from the sys module
To find the maximum and minimum values for integers in Python we can use the maxsize method from the sys module. The sys.maxsize gives us the maximum value whereas the negative version of this value i.e. -sys.maxsize-1 gives us the minimum value for the integer.
Syntax
The code can simply be written as follows:
import sys
# max integer value
int_max = sys.maxsize
# min integer value
int_min = -sys.maxsize - 1
print("maximum integer value: ", int_max)
print("The minimum integer value: ", int_min)
In the above code:
- We wrote the statement, “sys.maxsize” to find the maximum value of an integer.
- For minimum value, we wrote negation of the above statement i.e. “-sys.maxsize-1” or we can also write it as “~sys.maxsize”.
The output for the above query is:
Method 2: Using the Numpy module in Python
We can also find the maximum and minimum value of an integer in Python by using the Numpy module of Python. The numpy.iinfo() is the method available in Numpy to get the system size bits. This method returns the max and min values of the integers of different sizes.
Syntax
We can write its simple syntax as follows:
numpy.iinfo(numpy.int(Size_of_integer))
The size of the integer is passed into the function.
Let’s see how it works.
import numpy
# Finding the max and min val for int-8 size
print(numpy.iinfo(numpy.int8))
# Finding the max and min val for int-16 size
print(numpy.iinfo(numpy.int16))
# Finding the max and min val for int-32 size
print(numpy.iinfo(numpy.int32))
# Finding the max and min val for int-64 size
print(numpy.iinfo(numpy.int64))
The output of the above program will give the max and min values of the integers. The output looks like this:
This was all about finding the max and min values for integers.
Conclusion
In Python, a couple of methods are used to find the maximum and minimum values for integers. The first and the most common one is by using the maxsize method and the second one is by using the numpy.iinfo() method offered by Numpy. In this post, we have discussed both the methods along with the syntax as examples practically.