The array module stores numbers in a fixed C type rather than as individual Python objects. The type code chosen when the array is created determines how many bytes each element uses, meaning an array of a million values takes up much less memory than a list. Before Python 3.15, the narrowest floating-point code was 'f', a single-precision value of four bytes.
For example, three temperature readings stored as single-precision values occupy four bytes each:
from array import array
temps = array('f', [21.5, 22.0, 21.75])
print(temps) # array('f', [21.5, 22.0, 21.75])
print(temps.itemsize) # 4
The itemsize attribute reports the size of one element. Four bytes corresponds to the 32 bits of a C float, so the three values occupy twelve bytes in total.
Since Python 3.15, the 'e' type code stores values in the IEEE 754 binary16 format, known as half precision.
from array import array
temps = array('e', [21.5, 22.0, 21.75])
print(temps) # array('e', [21.5, 22.0, 21.75])
print(temps.itemsize) # 2
The values are unchanged and each element now occupies two bytes instead of four. For three readings the difference is irrelevant, but the saving scales with the amount of data. For example, a million readings use only 1.9 MiB instead of 3.8 MiB.
However, this comes at the cost of precision and range. Half-precision values provide about three decimal digits of accuracy and have a maximum value of 65504, making them suitable for measurements such as temperature but not for values requiring greater accuracy or a wider range.
Leave a Comment
Cancel reply