Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short Integers in Python

Tags:

Python allocates integers automatically based on the underlying system architecture. Unfortunately I have a huge dataset which needs to be fully loaded into memory.

So, is there a way to force Python to use only 2 bytes for some integers (equivalent of C++ 'short')?

like image 834
Arnav Avatar asked Sep 23 '08 10:09

Arnav


People also ask

What is int short for in Python?

int (signed integers) − They are often called just integers or ints. They are positive or negative whole numbers with no decimal point. Integers in Python 3 are of unlimited size. Python 2 has two integer types - int and long. There is no 'long integer' in Python 3 anymore.

What are the 3 types of numbers in Python?

There are three distinct numeric types: integers, floating point numbers, and complex numbers. In addition, Booleans are a subtype of integers. Integers have unlimited precision.

What is %s in int in Python?

%s can format any python object and print it is a string. The result that %d and %s print the same in this case because you are passing int/long object. Suppose if you try to pass other object, %s would print the str() representation and %d would either fail or would print its numeric defined value.

What is long integer in Python?

A long is an integer type value that has unlimited length. By converting a string into long we are translating the value of string type to long type. In Python3 int is upgraded to long by default which means that all the integers are long in Python3. So we can use int() to convert a string to long in Python.


2 Answers

Nope. But you can use short integers in arrays:

from array import array a = array("h") # h = signed short, H = unsigned short 

As long as the value stays in that array it will be a short integer.

  • documentation for the array module
like image 93
Armin Ronacher Avatar answered Sep 28 '22 09:09

Armin Ronacher


Thanks to Armin for pointing out the 'array' module. I also found the 'struct' module that packs c-style structs in a string:

From the documentation (https://docs.python.org/library/struct.html):

>>> from struct import * >>> pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) >>> calcsize('hhl') 8 
like image 27
Arnav Avatar answered Sep 28 '22 10:09

Arnav